[英]How do I get a file's directory using the File object?
考慮代碼:
File file = new File("c:\\temp\\java\\testfile");
testfile
是一個文件,它可能存在也可能不存在。 我想使用File
對象獲取目錄c:\\\\temp\\\\java\\\\
。 我該怎么做?
在任何一種情況下,我都希望file.getParent()
(或file.getParentFile()
)給你你想要的。
此外,如果您想確定原始File
是否確實存在並且是一個目錄,那么exists()
和isDirectory()
就是您所追求的。
Java 文檔中的File.getParent()
如果你做這樣的事情:
File file = new File("test.txt");
String parent = file.getParent();
parent
將為空。
因此,要獲取此文件的目錄,您可以執行以下操作:
parent = file.getAbsoluteFile().getParent();
文件 API File.getParent或File.getParentFile應返回您的文件目錄。
你的代碼應該是這樣的:
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 filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
dir=filePath.getAbsolutePath();
}
else
{
dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}
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()); }
String parentPath = f.getPath().substring(0, f.getPath().length() - f.getName().length());
這將是我的解決方案
2021 年 6 月 10 日所有當前答案都失敗了,例如。 給定的文件是...
new File("." + File.separator + "."); //Odd, yes, but I've seen similar more often than you'd think is possible
要獲得簡單、可靠的解決方案,請嘗試...
File givenFile = new File("." + File.separator + ".." + File.separator + "." + File.separator + "fakeFilename"); //The file or dir we want the parent of, whether it exists or not
File parentFile = new File(givenFile.getAbsolutePath() + File.separator + "..");
System.out.println(parentFile.getAbsolutePath());
請注意,此答案假定您想要filesystem 上的實際父目錄,而不是表示給定 File 對象的父節點的 File 對象(可能為空,也可能與給定文件位於同一目錄)。
編輯:另請注意,內部文件名並不簡潔,在某些情況下可能會隨着重復使用而增長。 沒有該問題的等效解決方案需要解析上述解決方案給出的整個絕對文件名,並調整輸出,刪除“.”的所有實例。 和“..”(后者的ofc還需要刪除它之前的節點,但只有在刪除所有“。”之后)
你可以用這個
File dir=new File(TestMain.class.getClassLoader().getResource("filename").getPath());
我發現這對於獲取絕對文件位置更有用。
File file = new File("\\TestHello\\test.txt");
System.out.println(file.getAbsoluteFile());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.