Rae Leng
Rae Leng

Reputation: 65

PrintWriter is only printing out the first line of the text file

I want the program to save each line of the text file i have into String s and print String s with a PrintWriter into another text file.

        File htmltext = new File(filepath);
        Scanner file = new Scanner(htmltext);
        
        PrintWriter out = new PrintWriter("updated.txt");
                
        while (file.hasNext()) {
            String s = file.nextLine(); 
            out.println(s);
            out.close();

I've run the code and out.println(s), only printed out the first time of the text file. I looked up how to print string into a text file and I found that I should use PrintWriter. I was expecting the program to basically "re-print" the content of the text document into the "updated.txt" file using PrintWriter. However, it only seems to be "re-printing" out the first line of the text file into "updated.txt".

I thought something was wrong with my while loop so I tried printing it out regularly into the console using System.out.println(s), but that worked fine.

What I understand of the while-loop is that while the file has tokens, it will iterate and s will store one line and (it should) print said string s.

What am I missing? Am I misunderstanding how the while-loop works? or how nextLine() works? or how PrintWriter works.(probably all of the above...)

I would love feedbacks!

Upvotes: 0

Views: 1020

Answers (3)

Don't close the write object before it is finished reading the whole content

File htmltext = new File(filepath);
Scanner file = new Scanner(htmltext);
PrintWriter out = new PrintWriter("updated.txt");
while (file.hasNext()) 
{
String s = file.nextLine(); 
out.println(s);
}

**out.close();**

Upvotes: 0

SurfMan
SurfMan

Reputation: 1813

Don't close the PrintWriter inside the loop. Do that after the while loop.

Upvotes: 0

Zachary Craig
Zachary Craig

Reputation: 2220

You're telling it to close as soon as it writes the line.

You want to move out.close to outside of your while loop, you should probably flush the stream as well.

Your code, in english, basically says:

open a scanner from stdin open a printwriter for a file

while the scanner has a new line
    write the new line to the printwriter
    **close the printwriter**

After the printwriter is closed, you can't write new data, because it's closed.

Upvotes: 0

Related Questions