Как получить каталог файлов с помощью объекта File?
Рассмотрим код:
File file = new File("c:\\temp\\java\\testfile");
testfile
является файлом, и он может существовать или не существовать.
Я хочу получить каталог c:\\temp\\java\\
с помощью объекта File
. Как мне это сделать?
Ответы
Ответ 1
В любом случае я ожидал бы file.getParent()
(или file.getParentFile()
), чтобы дать вам то, что вы хотите.
Кроме того, если вы хотите узнать, существует ли оригинальный File
и является ли он каталогом, то exists()
и isDirectory()
- это то, что вам нужно.
Ответ 2
File.getParent() из документации Java
Ответ 3
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 ");
}
Ответ 4
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());
}
Ответ 5
File filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
dir=filePath.getAbsolutePath();
}
else
{
dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}
Ответ 6
Если вы сделаете что-то вроде этого:
File file = new File("test.txt");
String parent = file.getParent();
parent
будет null.
Итак, чтобы получить каталог этого файла, вы можете сделать следующее:
parent = file.getAbsoluteFile().getParent();
Ответ 7
Вы можете использовать этот
File dir=new File(TestMain.class.getClassLoader().getResource("filename").getPath());
Ответ 8
String parentPath = f.getPath().substring(0, f.getPath().length() - f.getName().length());
Это будет мое решение
Ответ 9
Я нашел это более полезным для получения абсолютного местоположения файла.
File file = new File("\\TestHello\\test.txt");
System.out.println(file.getAbsoluteFile());