我遇到了File.mkdirs()的问题。我并行创建几百个文件夹,但似乎很少次,这个mkdir()api返回true但是文件夹并没有真正创建(java 1.8)。我在下面贴了我的示例代码,有什么想法吗?
我的示例代码和输出位于:https://pastebin.com/aYWDw6JZ 它大部分时间都会创建文件夹,但有时会失败。
public void run() {
// TODO Auto-generated method stub
long randData = (long) (System.currentTimeMillis() + (Math.random() * 100000));
String folderPath = File.separatorChar + "data" + File.separatorChar + "ext" + File.separatorChar + randData;
File testFolder = new File(folderPath);
if (!testFolder.exists()) {
if(testFolder.mkdirs() == false)
System.out.println(System.currentTimeMillis() + ": folder creation failed!");
}
String filename = testFolder + File.separator + "test.txt";
File testFile = new File(filename);
FileOutputStream fileOutputStream = null;
boolean bCreated = false;
try {
//Thread.sleep(1000);
if(testFolder.exists() == false) {
System.out.println("Folder not created!");
System.out.println("Folder: " + testFolder.getAbsolutePath() + " does not exist!");
}else
bCreated = true;
fileOutputStream = new FileOutputStream(testFile);
fileOutputStream.close();
testFile.delete();
testFolder.delete();
//System.out.println("success:" + testFile.getAbsolutePath());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Folder created? " + testFolder + ": " + bCreated);
//back off and see if the folder is really created
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Checking again, " + testFolder.getAbsolutePath() + " created? " + testFolder.exists());
}
}
输出:
java.io.FileNotFoundException: \data\ext\1521045935714\test.txt (The system cannot find the path specified)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
at DiskFolderCreationThread.run(DiskFolderCreationThread.java:30)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Folder created? \data\ext\1521045935714: true
Checking again, C:\data\ext\1521045935714 created? false
答案 0 :(得分:1)
只想更新我的发现作为解决方案。我发现在我的应用程序中,多个线程试图创建文件夹,并且如果两个线程同时试图创建具有相同名称的文件夹,我会看到这种mkdirs()行为,否则就可以了。我消除了这种情况,并确保文件夹名称在线程之间是唯一的,并且现在没有问题。