我目前遇到的问题是我遇到了一个我以前从未见过的异常,这就是我不知道如何处理它的原因。
我想根据给定的参数创建一个文件,但它不起作用。
public static Path createFile(String destDir, String fileName) throws IOException {
FileAccess.createDirectory( destDir);
Path xpath = new Path( destDir + Path.SEPARATOR + fileName);
if (! xpath.toFile().exists()) {
xpath.toFile().createNewFile();
if(FileAccess.TRACE_FILE)Trace.println1("<<< createFile " + xpath.toString() );
}
return xpath;
}
public static void createDirectory(String destDir) {
Path dirpath = new Path(destDir);
if (! dirpath.toFile().exists()) {
dirpath.toFile().mkdir();
if(TRACE_FILE)Trace.println1("<<< mkdir " + dirpath.toString() );
}
}
每次我运行我的应用程序时都会发生以下异常:
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
[...]
我该如何摆脱它? (顺便说一句,我使用的是 Win7 64 位)
最佳答案
问题是除非整个包含路径已经存在 - 它的直接父目录和它上面的所有父目录,否则无法创建文件。
如果您有一个路径 c:\Temp 并且其下没有子目录,并且您尝试创建一个名为 c:\Temp\SubDir\myfile.txt 的文件,这将失败,因为 C:\Temp\SubDir 没有存在。
之前
xpath.toFile().createNewFile();
添加
xpath.toFile().mkdirs();
(我不确定 mkdirs() 是否需要只是对象中的路径;如果需要,则将新行更改为
new File(destDir).mkdirs();
否则,您将获得创建为子目录的文件名!您可以通过检查 Windows 资源管理器以查看它创建了哪些目录来验证哪个是正确的。)
关于java - 在 java.io.WinNTFileSystem.createFileExclusively 中摆脱 java.io.Exception 很热吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9599621/