พิจารณารหัส:
File file = new File("c:\\temp\\java\\testfile");
testfile
เป็นไฟล์และอาจมีหรือไม่มีอยู่ ฉันต้องการรับไดเรกทอรีc:\\temp\\java\\
โดยใช้File
วัตถุ ฉันจะทำสิ่งนี้ได้อย่างไร?
พิจารณารหัส:
File file = new File("c:\\temp\\java\\testfile");
testfile
เป็นไฟล์และอาจมีหรือไม่มีอยู่ ฉันต้องการรับไดเรกทอรีc:\\temp\\java\\
โดยใช้File
วัตถุ ฉันจะทำสิ่งนี้ได้อย่างไร?
คำตอบ:
ไม่ว่าในกรณีใดฉันคาดหวังfile.getParent()
(หรือfile.getParentFile()
) ที่จะให้สิ่งที่คุณต้องการ
นอกจากนี้หากคุณต้องการทราบว่าต้นฉบับมีอยู่จริงหรือFile
ไม่และเป็นไดเร็กทอรีexists()
และisDirectory()
เป็นสิ่งที่คุณต้องการ
หากคุณทำสิ่งนี้:
File file = new File("test.txt");
String parent = file.getParent();
parent
จะเป็นโมฆะ
เพื่อรับไดเร็กทอรีของไฟล์นี้คุณสามารถทำได้ต่อไป:
parent = file.getAbsoluteFile().getParent();
File API File.getParentหรือFile.getParentFileควรส่งคืน Directory of file ให้คุณ
รหัสของคุณควรเป็นดังนี้:
File file = new File("c:\\temp\\java\\testfile");
if(!file.exists()){
file = file.getParentFile();
}
คุณสามารถตรวจสอบไฟล์พาเรนต์ของคุณเพิ่มเติมได้โดยใช้File.isDirectory API
if(file.isDirectory()){
System.out.println("file is directory ");
}
File directory = new File("Enter any directory name or file name"); boolean isDirectory = directory.isDirectory(); if (isDirectory) { // It returns true if directory is a directory. System.out.println("the name you have entered is a directory : " + directory); //It returns the absolutepath of a directory. System.out.println("the path is " + directory.getAbsolutePath()); } else { // It returns false if directory is a file. System.out.println("the name you have entered is a file : " + directory); //It returns the absolute path of a file. System.out.println("the path is " + file.getParent()); }
code
ไฟล์สุดท้าย = ไฟล์ใหม่ ("C: /dev/changeofseasons.mid"); System.out.println ("มีไฟล์อยู่หรือไม่" + file.exists ()); System.out.println ("ไดเร็กทอรีของไฟล์:" + file.getAbsolutePath ()); โอเคขอโทษสำหรับการเยื้องที่ง่อยฉันไม่คิดว่าจะจัดรูปแบบโค้ดในความคิดเห็นได้ ยังคงเห็นได้ชัดว่ารหัสของคุณใช้งานไม่ได้
File filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
dir=filePath.getAbsolutePath();
}
else
{
dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}
your_file_path = "C:\\testfiles\\temp\\testfile";
อย่างไร - ฉันไม่คิดว่ามันจะให้สิ่งที่คุณหวัง
คุณสามารถใช้สิ่งนี้
File dir=new File(TestMain.class.getClassLoader().getResource("filename").getPath());
String parentPath = f.getPath().substring(0, f.getPath().length() - f.getName().length());
นี่คงเป็นทางออกของฉัน
ฉันพบว่าสิ่งนี้มีประโยชน์มากขึ้นสำหรับการรับตำแหน่งไฟล์ที่แน่นอน
File file = new File("\\TestHello\\test.txt");
System.out.println(file.getAbsoluteFile());