Certainly! Below is an example code in Java that reads a text file into an array. This code reads the content of a text file line by line and stores each line in an element of a String array.

Example 1:

             java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class ReadFileToArray {
    public static void main(String[] args) {
        String filePath = "sample.txt";
        ArrayList<String> lines = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

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

        for (String l : linesArray) {
            System.out.println(l);
        }
    }
}

             

Explanation of the code:

1. We import necessary classes for file reading and handling.

2. Define the file path "sample.txt" and create an ArrayList to store the lines read from the file.

3. Use a try-with-resources block to open a BufferedReader to read the file.

4. Read each line from the file using `br.readLine()` and add it to the ArrayList `lines`.

5. Handle IOException in case file reading fails.

6. Convert the ArrayList `lines` to a String array `linesArray` using the `toArray()` method.

7. Loop through the `linesArray` and print each line using a foreach loop.

Output:

If the content of "sample.txt" is:

             
Hello
World
Java
Programming

             

The output of running the program would be:

             
Hello
World
Java
Programming

             

You can modify the file path "sample.txt" to point to the text file you want to read in the same directory as the Java file.

Was this article helpful?
YesNo

Similar Posts