0

我没有 iMac,但是 2 位用户在启动我的应用程序时在他们的 iMac 上遇到了同样的问题。应用程序首先通过以下代码在用户主文件夹中创建一个文件夹 + 一个文件(如果在其中找不到它们):

final String FILE_SEPARATOR = System.getProperty( "file.separator" );
File homeFolder = new File( System.getProperty( "user.home" ) + FILE_SEPARATOR + ".testAPP" + FILE_SEPARATOR + "database" );
String dataFilePath = homeFolder.getCanonicalFile() + FILE_SEPARATOR + "data.xml";
if( !homeFolder.exists() ) homeFolder.mkdirs();
File dataFile = new File( dataFilePath );               
dataFile.createNewFile();  // Throws IOException

这段代码在最后一行为他们俩抛出了这个异常:

java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)

导致这种情况的 iMac 是否有特定限制?

4

1 回答 1

0

通过 String concat 和 FILE_SEPARATOR 创建路径是一种不可靠的方式。mkdirs() 执行也可能失败,因此检查返回值很重要。试试这种方式:

File homeFolder = new File(System.getProperty("user.home"));
File testAppDir = new File(homeFolder, ".testAPP");
File databaseDir = new File(testAppDir, "database");
File dataFile = new File(databaseDir, "data.xml");
if (!databaseDir.isDirectory())
    if (!databaseDir.mkdirs())
        throw new IOException("Failed to create directory");
dataFile.createNewFile();
于 2012-07-08T09:16:35.453 回答