Câu trả lời:
Trong cả hai trường hợp, tôi mong đợi file.getParent()
(hoặc file.getParentFile()
) cung cấp cho bạn những gì bạn muốn.
Ngoài ra, nếu bạn muốn tìm hiểu xem bản gốc File
có tồn tại hay không và có phải là một thư mục exists()
hay isDirectory()
không thì bạn đang theo dõi.
Nếu bạn làm điều gì đó như thế này:
File file = new File("test.txt");
String parent = file.getParent();
parent
sẽ là null.
Vì vậy, để lấy thư mục của tệp này, bạn có thể làm tiếp theo:
parent = file.getAbsoluteFile().getParent();
File API File.getParent hoặc File.getParentFile sẽ trả về cho bạn Thư mục tệp.
Mã của bạn phải như sau:
File file = new File("c:\\temp\\java\\testfile");
if(!file.exists()){
file = file.getParentFile();
}
Ngoài ra, bạn có thể kiểm tra tệp mẹ của mình là thư mục bằng cách sử dụng API File.isDirectory
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
final File file = new File ("C: /dev/changeofseasons.mid"); System.out.println ("tệp tồn tại?" + Tệp.exists ()); System.out.println ("thư mục của tệp:" + file.getAbsolutePath ()); Ok, xin lỗi vì đã thụt lề sai, tôi không nghĩ rằng có thể định dạng mã trong nhận xét. Tuy nhiên, mã của bạn rõ ràng không hoạt động.
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";
- tôi không nghĩ nó sẽ mang lại những gì bạn hy vọng.