2012-07-08 137 views
0

我没有一台iMac,但2个用户对他们的iMac相同的问题时,他们开始我的申请。该应用程序首先创建一个文件夹+里面一个文件,如果他们都没有找到,在用户主文件夹,通过这个代码:创建文件的iMac抛出IOException异常

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有特定的限制?

+0

我想在我的MacBook Pro(Mac OSX版10.7.4)你的代码,它的工作原理:它创建的文件夹,并没有错误的文件。 – user1498339 2012-07-08 09:19:35

回答

0

通过使用concat和FILE_SEPARATOR创建pathes是一种不可靠的方法。 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(); 
+0

非常感谢。我会尝试。我只是想,可能会使用mkdirs()失败,因为它有2个文件夹,它不得不创建,而不仅仅是一个..可能是? – Brad 2012-07-08 09:28:01