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
You forgot to close() the writer, so you never gave it a chance to flush buffered output to disk.
Two things.
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
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();
}
}
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)