Answers:
无论哪种情况,我都希望file.getParent()
(或file.getParentFile()
)给您您想要的。
另外,如果您要查找原始目录是否File
确实存在并且是目录,那么您将要查找exists()
and isDirectory()
。
文件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 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
最终文件file = new File(“ 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";
-我认为它不会如您所愿。