bufferedwriter stops in the middle of writing

前端 未结 4 703
长情又很酷
长情又很酷 2021-01-18 02:39

For some reason this code results in a truncated text.txt file. It should (according to me) write out 1000 results, but the output file has various amounts of lines (dependi

相关标签:
4条回答
  • 2021-01-18 02:56

    You forgot to close() the writer, so you never gave it a chance to flush buffered output to disk.

    0 讨论(0)
  • 2021-01-18 03:01

    Two things.

    1. Flush the stream
    2. Close the stream

    Try something like:

     Writer out = null;
     try {
        out = new BufferedWriter(new FileWriter("test.txt"),16*1024);
    
        // Write some stuff
    
        out.flush();
     } finally {
        try {
            out.close();
        } catch (Exception exp) {
        }
    }
    

    Try and remember, it's a "buffer". That means that it's keeping stuff stored in memory until it decides it needs to be written or your explicitly ask it to "flush" it's contents.

    Also, you should always close your streams. This prevents possible locked file issues and file handle issues :P

    0 讨论(0)
  • 2021-01-18 03:17

    You should consider flushing your stream after each write. Try something like this:

    try{
        //your code
        out.write("" + i + ", " + red + ", " + green + ", " + blue
                + ", " + (.21 * red + .71 * green + 0.08 * blue + "\n"));
        i++;
    }finally{
        //Close the stream
        out.close();
    }
    

    Also you should make sure that you close your stream at the end of your operation. A good way to structure your program might be this:

    Random generator = new Random();
    float red = 0, green = 0, blue = 0;
    int i = 0;
    
    Writer out = null;
    
    try{
        out = new BufferedWriter(new FileWriter("test.txt"), 16 * 1024);
    
        while (i < 1000) {
            //your logic
            if (red < 256 && blue < 256 && green < 256) {
                    out.write("" + i + ", " + red + ", " + green + ", " + blue
                            + ", " + (.21 * red + .71 * green + 0.08 * blue + "\n"));
                    i++;
            }
        }
    }finally{
        if(out != null){
            out.close();
        }
    }
    
    0 讨论(0)
  • 2021-01-18 03:17

    Once you open io (Reader, Writter or BufferR/W, ...), you have to close it later to close that stream and release the resource. Incase your code has nested stream (File, FileReader, BufferedReader) or (Writer1, Writer2), you have to close it separately order right after(BufferedReader, FileReader, File) or (Writer1.close() before using Writer2)

    0 讨论(0)
提交回复
热议问题