質問

Why is myfile.txt empty? I am try append contents to myfile.txt but when I open it it is still empty. File is getting created.

import java.io.*;

public class NewClass1 {
    @SuppressWarnings("empty-statement")
    public static void main(String[] args) throws IOException{
        File inputFile = new File("input.txt");
        FileReader in1=null; 
        in1 = new FileReader("input.txt");
        char c;
        int count=0;
        int r;
        String s="";     
        File file;
        file = new File("myfile.txt");
        file.createNewFile();
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true))); 

        while((r=in1.read())!=-1) {
            c = (char)r;
            s=s+c;

            if (c == '1' ) {
                count++;
            }
            if (c == '\n') {
                 if (count>1) {
                     out.print(s); 
                 }
                 s = "";
                 count=0;
            }
        }
    }       
}
役に立ちましたか?

解決

You have to flush and close the output file for it to actually save that last buffer full of characters to the disk.

out.flush();
out.close();

The purpose of BufferedWriter is to hold those characters in a buffer in memory until such time as you flush the buffer.

Calling 'close' is supposed to flush as well, so calling that should cause the buffer to be written as well.

There are other possible reasons: I assume you have checked that input.txt is not empty, and that it has at least one newline (\n) in it. This algorithm will write only when it sees a newline, and if no newline exists it will write nothing.

Finally, I don't recommend using 'FileWriter' because the character encoding depends on your operating environment, which can change. It is better to specify 'UTF-8' (or some other specific character encoding) with a OutputStreamWriter and a FileOutputStream.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top