반응형
파일을 사용하여 파일의 디렉토리를 어떻게 얻습니까?
코드를 고려하십시오.
File file = new File("c:\\temp\\java\\testfile");
testfile
파일이며 존재하거나 존재하지 않습니다. 객체를 c:\\temp\\java\\
사용하여 디렉토리를 소유하고 File
있습니다. 어떻게해야합니까?
두 경우 모두 원하는 제공하기를 기대합니다 (또는 ).file.getParent()
file.getParentFile()
원래이 있는지 여부를 찾으려면 또한, File
하지 존재를하고 있습니다 다음, 디렉토리 exists()
및 isDirectory()
당신은 후이야 무슨.
Java 문서의 File.getParent ()
다음과 같이하면 :
File file = new File("test.txt");
String parent = file.getParent();
parent
null이됩니다.
따라서이 파일의 디렉토리를 얻으려면 다음을 수행하십시오.
parent = file.getAbsoluteFile().getParent();
File 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()); }
File filePath=new File("your_file_path");
String dir="";
if (filePath.isDirectory())
{
dir=filePath.getAbsolutePath();
}
else
{
dir=filePath.getAbsolutePath().replaceAll(filePath.getName(), "");
}
사용할 수 있습니다.
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());
참고 URL : https://stackoverflow.com/questions/3657157/how-do-i-get-a-files-directory-using-the-file-object
반응형
'IT' 카테고리의 다른 글
객체를 실제 유형으로 캐스팅하는 방법은 무엇입니까? (0) | 2020.08.20 |
---|---|
나머지 Django없이 Django 템플릿을 어떻게 사용합니까? (0) | 2020.08.20 |
Runtime.exec ()에서 파이프를 작동시키는 방법은 무엇입니까? (0) | 2020.08.20 |
HashMap 및 int를 키로 (0) | 2020.08.20 |
삼각 함수는 어떻게 작동합니까? (0) | 2020.08.20 |