我想通過Java中的多個線程將一些內容寫入文件。每個線程讀取不同的輸入文件,進行一些計算並將一些(不同的)內容寫入公共輸出文件。問題在於最終輸出文件只包含最後一個終止線程寫入的內容,而不包含其他線程寫入的內容。線程的相關代碼 -Java - 寫入同一文件的多個線程
public void run()
{
try
{
File file = new File("/home/output.txt");
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
BufferedReader br = new BufferedReader(new FileReader(inputfile)); // each thread reads a different input file
String line="";
while((line=br.readLine())!=null)
{
String id = line.trim(); // fetch id
StringBuffer sb = processId(userId); // process id
synchronized(this){
bw.write(sb.toString() + "\n"); // write to file
}
}
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
如何讓所有線程將其內容寫入公共文件?
你必須追加到現有的文件(''FileOutputStream''有一個布爾標誌)。但是你也必須寫''synchronized'',以確保只有一個線程同時寫入。 – qqilihq
如果您可以使用StringBuilder,請勿使用StringBuffer。在這種情況下processId()可以返回一個String。 –
您需要在所有線程中打開該文件並協調其寫作。否則,你很可能會陷入混亂。我建議你有一個單線程執行程序並提交任務給它寫入文件。這將確保單線程寫入。 –