java bufferedreader read all lines

java bufferedreader read all lines

To read all the lines of a file in Java using the 'BufferedReader' class, you can use the 'readLine' method in a loop while there are more lines to read. Here's an example of how to do this:

r‮fe‬er to:lautturi.com
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    try {
      // Opens the file for reading
      BufferedReader reader = new BufferedReader(new FileReader("file.txt"));

      // Creates a list to store the read rows
      List<String> linhas = new ArrayList<>();

      // Reads the lines of the file while there are more lines to read
      String linha;
      while ((linha = reader.readLine()) != null) {
        linhas.add(linha);
      }

      // Closes the file
      reader.close();

      // Do something with the lines read here...
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

This will read all the lines in the file and store them in a list of strings. Then you can do whatever you want with this list, such as printing the lines or processing them in some other way.

Note that you need to handle the 'IOException' exception if an error occurs when opening the file or reading the lines. In addition, it is important to remember to close the file when you are finished reading, to free up system resources.

If you want to read all the lines of a file in a single string, you can use the 'lines' method of the 'Files' class of the 'java.nio.file' library instead of 'BufferedReader'. Here's an example of how to do this:

import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    try {
      // Reads all lines of the file in a single string
      String texto = Files.readString(Paths.get("arquivo.txt"));

      // Do something with the text here...
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

This will read the entire contents of the file in a single string, including the new line characters.

Created Time:2017-11-03 00:14:46  Author:lautturi