1
讓我來解釋一下情況。在Windows操作系統中。當java程序使用FileOutputStream寫入文件時,我同時粘貼文件,拋出FileNotFoundException
我的java程序寫入日誌文件。
通常這是確定的,但是當我複製和粘貼日誌文件(CTRL + C和V), java的拋出異常
java.io.IOException: java.io.FileNotFoundException: C:\log.txt (The process cannot access the file because it is being used by another process)
後,我研究這個問題,我發現此異常粘貼文件拋出。不復制。
請告訴我爲什麼會發生此異常。
重現代碼如下(編碼「Windows-31J」是日語,沒有 特殊含義)。請執行此程序並複製並粘貼「C:\ log.txt」。
package test;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.stream.IntStream;
public class FileNotFound {
public static void main(String[] args) {
IntStream.range(0, 100000).parallel().forEach(
i -> {
try {
fileWrite("C:\\log.txt", String.valueOf(i));
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
public static void fileWrite(String filePath, String str) throws IOException {
try (FileOutputStream fw = new FileOutputStream(filePath, true);
OutputStreamWriter ow = new OutputStreamWriter(fw, "Windows-31J");
BufferedWriter bw = new BufferedWriter(ow);
PrintWriter out = new PrintWriter(bw)) {
out.println(str);
} catch (IOException e) {
throw new IOException(e);
}
}
}
謝謝,這也就不足爲奇了。但過去的Windows快捷鍵(Ctrl + V)獲得排他鎖? –
我不明白爲什麼它會是除複製步驟(Ctrl/c)以外的其他任何東西。 – EJP