เมื่อใช้
file.createNewFile();
ฉันได้รับข้อยกเว้นดังต่อไปนี้
java.io.IOException: Parent directory of file does not exist: /.../pkg/databases/mydb
ฉันสงสัยว่ามี createNewFile ที่สร้างไดเร็กทอรีหลักที่ขาดหายไปหรือไม่?
เมื่อใช้
file.createNewFile();
ฉันได้รับข้อยกเว้นดังต่อไปนี้
java.io.IOException: Parent directory of file does not exist: /.../pkg/databases/mydb
ฉันสงสัยว่ามี createNewFile ที่สร้างไดเร็กทอรีหลักที่ขาดหายไปหรือไม่?
คำตอบ:
คุณลองสิ่งนี้แล้วหรือยัง?
file.getParentFile().mkdirs();
file.createNewFile();
ฉันไม่รู้วิธีเรียกวิธีเดียวที่จะทำสิ่งนี้ แต่มันค่อนข้างง่ายเหมือนสองคำสั่ง
mkdirsหากไฟล์ที่คุณพยายามสร้างไม่ได้อยู่ในไดเร็กทอรีที่ไม่มีอยู่จริง แต่กรณีการใช้งานของฉันคือฉันกำลังสร้างไฟล์หลายไฟล์ซึ่งบางไฟล์มีไดเร็กทอรีหลักในขณะที่ไฟล์อื่นไม่มี
<parent-dir>/<file-name>คำตอบของจอนทำงานหากคุณแน่ใจว่าสตริงเส้นทางที่คุณกำลังสร้างไฟล์รวมถึงไดเรกทอรีผู้ปกครองเช่นถ้าคุณแน่ใจว่าเส้นทางที่อยู่ในรูป
ถ้ามันไม่ได้คือมันเป็นทางญาติของรูปแบบ<file-name>แล้วจะกลับมาgetParentFile()null
เช่น
File f = new File("dir/text.txt");
f.getParentFile().mkdirs(); // works fine because the path includes a parent directory.
File f = new File("text.txt");
f.getParentFile().mkdirs(); // throws NullPointerException because the parent file is unknown, i.e. `null`.
ดังนั้นหากเส้นทางไฟล์ของคุณอาจมีหรือไม่มีไดเร็กทอรีหลักคุณจะปลอดภัยยิ่งขึ้นด้วยรหัสต่อไปนี้:
File f = new File(filename);
if (f.getParentFile() != null) {
f.getParentFile().mkdirs();
}
f.createNewFile();
ตั้งแต่ java7 คุณยังสามารถใช้ NIO2 API:
void createFile() throws IOException {
Path fp = Paths.get("dir1/dir2/newfile.txt");
Files.createDirectories(fp.getParent());
Files.createFile(fp);
}
new File("file.txt").getParentFile()ผลตอบแทนnull,new File("dir/file.txt").getParentFile()ผลตอบแทนเช่นเดียวกับnew File("dir")