programing

File 객체를 사용하여 파일 디렉토리를 가져오려면 어떻게 해야 합니까?

randomtip 2022. 10. 2. 11:09
반응형

File 객체를 사용하여 파일 디렉토리를 가져오려면 어떻게 해야 합니까?

코드를 고려합니다.

File file = new File("c:\\temp\\java\\testfile");

testfile파일일 수도 있고 존재하지 않을 수도 있습니다.나는 디렉토리를 얻고 싶다.c:\\temp\\java\\사용방법File물건.이걸 어떻게 해야 하죠?

어느 쪽이든 당신이 원하는 것을 줄 수 있을 겁니다.

또한 원본이 다음 중 어느 쪽인지 알고 싶다면File 존재하며 디렉토리입니다.exists()그리고.isDirectory()네가 원하는 게 그거야

Java 문서의 File.getParent()

다음과 같은 작업을 수행할 경우:

File file = new File("test.txt");
String parent = file.getParent();

parent무효가 됩니다.

이 파일의 디렉토리를 취득하려면 , 다음의 조작을 실시합니다.

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 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());

이 답변에서는 파일시스템상의 실제 부모 디렉토리가 필요한 것을 전제로 하고 있으며, 지정된 파일오브젝트의 부모 노드를 나타내는 파일오브젝트(늘일 수도 있고 지정된 파일과 같은 디렉토리일 수도 있음)가 아닌 것에 주의해 주십시오.

편집: 또한 내부 파일 이름이 간단하지 않으며 반복 사용으로 인해 커질 수 있습니다.이 문제가 없는 동등한 솔루션에서는 위의 솔루션에서 주어진 절대 파일 이름 전체를 해석하고 출력을 조정하여 "." 및 ".." 인스턴스를 모두 삭제해야 합니다(후자 ofc는 노드도 삭제하기 전에 삭제해야 합니다만, "."가 모두 삭제되어야 합니다).

이거 써도 돼

 File dir=new File(TestMain.class.getClassLoader().getResource("filename").getPath());

나는 이것이 절대 파일 위치를 얻는 데 더 유용하다는 것을 알았다.

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

반응형