2017-09-27 65 views
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); 
    } 
    } 
} 

回答

0

它的发生是因为另一个进程,即你的资源管理器窗口,正在使用该文件,通过“复制”操作,它的Windows不允许。解决方案:不要。

+0

谢谢,这也就不足为奇了。但过去的Windows快捷键(Ctrl + V)获得排他锁? –

+0

我不明白为什么它会是除复制步骤(Ctrl/c)以外的其他任何东西。 – EJP

相关问题