Question

I'm trying to read text from file, do some operation and output result in a different file but for some reason it only prints one line of the results.

    Scanner file = new Scanner(new FileInputStream("/.../file.txt"));
    PrintWriter p = new PrintWriter(new FileWriter("/.../output.txt"));

    int count = 0;

    while (file.hasNextLine()) 
    {
        String s = file.nextLine();
        count++; 
        try
        {
            if(s.contains("#AVFC")){
                p.printf("There are %d words on this line ", s.split("\\s").length-1);
                p.println(count);
                p.close();

            }
        }
        catch(Exception ex){ 
            ex.printStackTrace(); 
        } 



    }
    file.close();

this is output;

There are 4 words on this line 1

but the output should be:

There are 4 words on this line 1

There are 10 words on this line 13

There are 8 words on this line 16
Was it helpful?

Solution

Why you close p in while loop?

Scanner file = new Scanner(new FileInputStream("/.../file.txt"));
PrintWriter p = new PrintWriter(new FileWriter("/.../output.txt"));

int count = 0;

while (file.hasNextLine()) 
{
    String s = file.nextLine();
    count++; 
    try
    {
        if(s.contains("#AVFC")){
            p.printf("There are %d words on this line ", s.split("\\s").length-1);
            p.println(count);

        }
    }
    catch(Exception ex){ 
        ex.printStackTrace(); 
    } 



}

p.close();
file.close();

in your code PrintWriter closed on first match found in file and other matches will not write in output file because you closed file writer before.

OTHER TIPS

Do not close your PrintWriter within the loop. (you still need it.) Just close it after the loop.

 while(file.hasNextLine())
 { 
    // your code goes here...
 }
 p.close();
 file.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top