I met a problem with BufferedWriter
when I write data to a single file with some threads.
I set the buffer size of the BufferedWriter
, but no matter what number I set, it flushes the data to disk when the buffer is 8192 (the default buffer size), not the size I set (here is 16384). Is there a problem with my code?
This is how I'm constructing the BufferedWriter
:
new BufferedWriter(new FileWriter(fileName, true), 16384);
This is the full code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Test1 {
public static void main(String[] args) throws IOException {
for(int i =0;i<10;i++){
MyThread r = new MyThread();
Thread t = new Thread(r);
t.start();
}
}
}
class MyThread implements Runnable {
public void run() {
String s = "{addffffffkkkljlkj2015dd}\n";
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(
"/Users/liaoliuqing/Downloads/1.txt", true),16384);
} catch (IOException e) {
e.printStackTrace();
}
for(int i =0 ; i<1000; i++){
try {
bw.write(String.format("%03d", i)+s);
//bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileWriter
buffers internally: #6108543 The doc says "To specify [character encoding and byte-buffer size] yourself, construct an OutputStreamWriter on a FileOutputStream", but I don't see a constructor for either of those classes that lets you specify a buffer size :( – Hassett