bufferedwriter stops in the middle of writing

前端 未结 4 741
长情又很酷
长情又很酷 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 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();
        }
    }
    

提交回复
热议问题