To read strings separated by newline using BufferedReader into a String array in Java, you can follow these steps:

  1. Initialize a BufferedReader object to read from an input source such as a file, an InputStream, or a Reader. For example:

    java
    BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
  2. Declare a List<String> to store the strings that you will read. For example:

    java
    List<String> lines = new ArrayList<>();
  3. Use a loop to read each line from the BufferedReader object until there are no more lines to read. For each line, add it to the List<String> object. For example:

    java
    String line; while ((line = reader.readLine()) != null) { lines.add(line); }
  4. Convert the List<String> to a String[] using the toArray() method. For example:

    java
    String[] linesArray = lines.toArray(new String[0]);

Putting it all together, here's an example code snippet:

java
import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader("file.txt")); List<String> lines = new ArrayList<>(); String line; while ((line = reader.readLine()) != null) { lines.add(line); } reader.close(); String[] linesArray = lines.toArray(new String[0]); for (String s : linesArray) { System.out.println(s); } } }

In this example, the BufferedReader object reads from a file called "file.txt". The List<String> object stores the lines that are read from the file using the readLine() method. Finally, the toArray() method is used to convert the List<String> to a String[]. The for loop prints each string in the array to the console.

Have questions or queries?
Get in Touch