문제

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
도움이 되었습니까?

해결책

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.

다른 팁

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top