Search code examples
javabufferedreader

Reading in text file in Java


I wrote some code to read in a text file and to return an array with each line stored in an element. I can't for the life of me work out why this isn't working...can anyone have a quick look? The output from the System.out.println(line); is null so I'm guessing there's a problem reading the line in, but I can't see why. Btw, the file i'm passing to it definitely has something in it!

public InOutSys(String filename) {
    try {
        file = new File(filename);
        br = new BufferedReader(new FileReader(file));
        bw = new BufferedWriter(new FileWriter(file));
    } catch (Exception e) {
        e.printStackTrace();
    }
}



public String[] readFile() { 

    ArrayList<String> dataList = new ArrayList<String>();   // use ArrayList because it can expand automatically
    try {
        String line;

        // Read in lines of the document until you read a null line
        do {
            line = br.readLine();
            System.out.println(line);
            dataList.add(line);
        } while (line != null && !line.isEmpty());
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    //  Convert the ArrayList into an Array
    String[] dataArr = new String[dataList.size()];
    dataArr = dataList.toArray(dataArr);

    // Test
    for (String s : dataArr)
        System.out.println(s);

    return dataArr; // Returns an array containing the separate lines of the
    // file
}

Solution

  • First, you open a FileWriter once after opening a FileReader using new FileWriter(file), which open a file in create mode. So it will be an empty file after you run your program.

    Second, is there an empty line in your file? if so, !line.isEmpty() will terminate your do-while-loop.