Ryan Stone
Ryan Stone

Reputation: 15

Reading a file in java error

Hi I have been using the Buffered Reader to try to read a text file and print how many lines the text file has. My code goes like this...

File parent = new File("/Desktop/Test Folder");
File text = new File(parent, "/text.txt");
FileWriter fw;
FileReader fr;
BufferedWriter write;
BufferedReader read;
if (!parent.exists()) {
        parent.mkdir();
    }
    try {
        text.createNewFile();
    } catch (Exception ex) {
        System.err.println("Error creating file");
    }
    try {
        fw = new FileWriter(text);
        fr = new FileReader(text);
        write = new BufferedWriter(fw);
        read = new BufferedReader(fr);
    } catch (Exception ex) {
        System.err.println("Error trying to write or read file");
    }
    System.out.println("Writing to file...");
try {
        write.write("String number one.\n");
        write.write("String number two.\n");
        List<String> lines = new LinkedList<String>();
        String line = read.readLine();
        while (line != null) {
            lines.add(line);
            line = read.readLine();
        }
        System.out.printf("Number of lines is %d.\n", lines.size());
        write.flush();
        write.close();
    } catch (Exception ex) {
        System.err.println("Error writing to file");
    }

When I run this it says that there are 0 elements in List lines. Any help? Did I make a carless mistake somewhere or am I using the wrong method? I am a amateur so I suspect the error is something obvious. Anyways, can anyone give me some help?

Upvotes: 0

Views: 190

Answers (2)

nansen
nansen

Reputation: 2952

you should put the flush() and close() of the Writer before the actual reading. What you are trying to do is using the file as a pipe. That is not what you want to do I guess.

Upvotes: 0

michele b
michele b

Reputation: 1865

Did you try to move the writer.flush(); call before the readLine() one?

From the documentation of Writer.flush():

Flush the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination

So if you're reading before flushing your file may be empty!

Upvotes: 1

Related Questions