William
William

Reputation: 21

Error is occurred during reading a text file (.txt) in Java

My java code to read a text file is as below:

package practice.java;
import java.io.IOException;

public class SearchFiles {
    public static void main(String[] args) throws IOException {
        String file_name = "C:/Java/test.txt";

        try {
            ReadFile file = new ReadFile(file_name);
            String[] aryLines = file.OpenFile();

            int i;
            for (i=0; i < aryLines.length; i++) {
                System.out.println(aryLines[i]);
            }
        }
        catch (IOException e) {
            System.out.println( e.getMessage() );
        }
    }
}

The following is the other code:

package practice.java;

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

public class ReadFile {
    private String path;

    public ReadFile (String file_path) {
        path = file_path;
   }


    public String[] OpenFile() throws IOException {

        FileReader fr = new FileReader(path);
        BufferedReader textReader = new BufferedReader(fr);

        int numberOfLines = readLines();
        String[] textData = new String[numberOfLines];

        int i;

        for (i=0; i < numberOfLines; i++) {
            textData[i] = textReader.readLine();
        }

        textReader.close();
        return textData;
        }

        int readLines() throws IOException {

            FileReader file_to_read = new FileReader(path);
            BufferedReader bf = new BufferedReader(file_to_read);

            String aLine;
            int numOfLines = 0;

            while ((aLine = bf.readLine()) != null) {
                numOfLines++;
            }    
            bf.close();

            return numOfLines;
        }
    }

And the outcome is null. What am I doing wrong? Which parts do I correct?

Upvotes: 0

Views: 2390

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

You are reading the file through to determine the number of lines. Then you try to read it again to actually read and capture the lines. This is a lot of unnecessary work. If you use a List<String>, you don't need this two-pass operation. Try this instead:

public List<String> OpenFile() throws IOException {

    List<String> lines = new ArrayList<String>();
    FileReader fr = new FileReader(path);
    BufferedReader textReader = new BufferedReader(fr);
    try {
        String aLine;
        while ((aLine = bf.readLine()) != null) {
            lines.add(aLine);
        }
    } finally {
        textReader.close();
    }
    return lines;
}

If you really need a String[] and not a List<String>, you can convert the list to an array. Just change the method return type and then replace the line return lines; with this:

    return lines.toArray(new String[0]);

Upvotes: 1

Related Questions