【问题标题】:java Failed to create new file in windows 7?java无法在Windows 7中创建新文件?
【发布时间】:2011-11-17 15:17:57
【问题描述】:

我正在尝试使用

在 Windows 7 中创建新文件
file.createNewFile()

但是文件没有创建,我得到了以下异常

Message:
The system cannot find the path specified
Stack Trace:
[java.io.IOException: The system cannot find the path specified,
    at java.io.WinNTFileSystem.createFileExclusively(Native Method),
    at java.io.File.createNewFile(File.java:883),
    at com.mercury.mtf.actions.file.CreateEmptyFileTask.execute(CreateEmptyFileTask.java:56),
    at com.mercury.mtf.actions.file.CreateEmptyFileAction.execute(CreateEmptyFileAction.java:42),
    at com.mercury.mtf.core.AbstractAction.run(AbstractAction.java:50),
    at com.mercury.mtf.core.Unit.runUnitAction(Unit.java:347),
    at com.mercury.mtf.core.Unit.executeUnitAction(Unit.java:176),
    at com.mercury.mtf.core.Unit.run(Unit.java:121),
    at com.mercury.mtf.core.execution.DefaultUnitExecutor.call(DefaultUnitExecutor.java:24),
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303),
    at java.util.concurrent.FutureTask.run(FutureTask.java:138),
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98),
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:207),
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886),
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908),
    at java.lang.Thread.run(Thread.java:619)]

我确定该路径存在,但我意识到该文件夹​​标记为只读。我试图删除只读标志,但我无法让它工作。

【问题讨论】:

    标签: java io java-io


    【解决方案1】:

    使用File newFile=new File(folderName+chipItems[i]); 而不是File newFile=new File(folderName+chipItems[i], "w");。那会好的。当您想提供 Unix touch 命令之类的功能时,请避免使用文件模式。

    【讨论】:

      【解决方案2】:

      如果文件是临时文件,你可以使用这个功能,你可以忘记所有的权限问题:

      File.createTempFile("prefix", "suffix") 
      

      【讨论】:

        【解决方案3】:

        确保您的路径分隔符正确。您可以使用单正斜杠或双反斜杠。例如,

        File f = new File("C:\\Documents and Settings\\thandasoru\\My Documents\\temp.txt");
        f.createNewFile();
        

        【讨论】:

        • 这可以使用File.separatorFile.separatorChar 解决。顺便说一句,这两个静态 final 字段不遵循 Java 命名约定。
        • 啊,没错!我忘了有 File.separatorChar 属性。上面提到的代码是肮脏的修复我会说;-)