0

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?

1
  • You need to flush() the output before you can read it from the file. Commented Mar 23, 2012 at 21:45

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

close() calls flush()... so only close() needed. docs.oracle.com/javase/6/docs/api/java/io/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.