0

In java: I am reading a file named fn. It is a text file, and the first number gives the number of lines and characters:

Example:

4
AFBA\n 
BBBB\n 
EFHE\n 
EFJH\n 

Theres a new line after each 4 characters. This goes for 4 rows.

What I have so far is:

File fp = new File(fn);
FileReader fr = new FileReader(fp);
BufferedReader bfr = new BufferedReader(fr);

How do I create a java algorithm to store this data in a data structure, such as an array list, array, stack, etc.

Thanks so much. I'm just getting started programming so sorry if this question doesn't match the Stack overflow rhetoric.

snowbarr
  • 11
  • 1

2 Answers2

2

You can use Java 8 Stream API and nio library to store each line as an object in a collection. For example:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
import java.util.*;

public class streamFileRead {

    public static void main(String args[]) {

        String fileName = "drive://location//fn.txt";
        List<String> list = new ArrayList<String>();
        
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

            list = stream.collect(Collectors.toList());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

I guarantee this is way more fast and foolproof than reading each line using a loop and identifying line breaks using \n.

Ayush28
  • 359
  • 3
  • 18
0

You can try this :

class ReadFile{
    public static void main(String[] args) throws IOException {
        File fp = new File(fn);
        FileReader fr = new FileReader(fp);
        BufferedReader bfr = new BufferedReader(fr);
        List<String> list= new ArrayList<>();
        String s="";
        while( (s=(bfr.readLine()))!=null){
            list.add(s);
        }
        System.out.print(list);
    }
}
Charul
  • 202
  • 2
  • 12