0

I'm trying to read a text and saving every line it has into a new element of an ArrayList. Is there anyway to continue reading and adding in the ArrayList until it gets to the end of file or whenever the reader doesnt find any other line to read?

Besides, what's best to use? Scanner or BufferedReader?

  • yes, there is a way to do that. Each has its uses. Take a look at this for scanner vs bufferedReader. http://stackoverflow.com/questions/2231369/scanner-vs-bufferedreader – austin wernli Mar 29 '16 at 19:27

5 Answers5

3

Traditionally, you'd do these operations:

  • Create an instance of a Scanner or BufferedReader
  • Set conditions to continually read the file (with a Scanner, through scanner.hasNextLine(); with a BufferedReader, there's a little bit more work to do)
  • Get the next line from either and add it to your list.

However, with Java 7's NIO library, you don't need to do that at all.

You can leverage Files#readAllLines to accomplish exactly what it is you want; no need to do any of the iteration yourself. You do have to provide a path to the file and a character set (i.e. Charset.forName("UTF-8");), but it works essentially the same.

Path filePath = Paths.get("/path/to/file/on/system");
List<String> lines = Files.readAllLines(filePath, Charset.forName("UTF-8"));
Makoto
  • 104,088
  • 27
  • 192
  • 230
1

Try using BufferedReader like this:

static List<String> getFileLines(final String path) throws IOException {

    final List<String> lines = new ArrayList<>();

    try (final BufferedReader br = new BufferedReader(new FileReader(path))) {
        string line = null;
        while((line = br.readLine()) != null) {
            lines.add(line);
        }
    }

    return lines;
}
  • Create an empty list for the results to go.
  • Use a try-with-resources Statement on the BufferedReader to safely open and close a file
  • Read lines until the BufferedReader returns null
  • return the list
flakes
  • 21,558
  • 8
  • 41
  • 88
1

FWIW, if you are using Java8, you can make use of the the stream APIs, as shown below

public static void main(String[] args) throws IOException {

    String filename = "test.txt"; // Put your filename
    List fileLines = new ArrayList<>();

    // Make sure to add the "throws IOException" to the method  
    Stream<String> fileStream = Files.lines(Paths.get(filename));
    fileStream.forEach(fileLines::add);        
}

I've a main method here, just put this in your method and add the throws statement or a try-catch block

You also could convert the above to a one liner as

((Stream<String>)Files.lines(Paths.get(filename))).forEach(fileLines::add);
Some guy
  • 1,210
  • 1
  • 17
  • 39
1

Since you want to read an entire line from a particular text file, i would recommend you to use the BufferedReader class.

You can create a BufferedReader object like this:

BufferedReader br = new BufferedReader(new FileReader(filenName));//fileName is a string
//that contains the name of the file if its in the same folder or else you must give the relative/absolute path to the file

Then use the readLine() function on the BufferedReader object to read each line of the file. You can try something like the following.

    try
    {
        //read each line of the file
        while((line = br.readLine()) != null)//if it reaches the end of the file rd will be null
        {
          //store the contents of the line into an ArrayList object
        }
    }catch(IOException ex)
    {
        System.out.println("Error");
    }
theVoid
  • 743
  • 4
  • 14
0

You might use

final List<String> lines =
   Files.lines(Paths.get(path)).collect(Collectors.toList());

or the variant with lines(Path, Charset).

aventurin
  • 2,056
  • 4
  • 26
  • 30