我面临 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