Programing

특정 파일의 상위 디렉토리 이름을 얻는 방법

crosscheck 2020. 8. 18. 07:13
반응형

특정 파일의 상위 디렉토리 이름을 얻는 방법


dddtest.java가있는 경로 이름에서 가져 오는 방법 .

File file = new File("C:/aaa/bbb/ccc/ddd/test.java");

사용 FilegetParentFile()방법String.lastIndexOf()검색 할 단지 바로 위 부모 디렉토리를.

Mark의 의견은 다음보다 더 나은 솔루션입니다 lastIndexOf().

file.getParentFile().getName();

이러한 솔루션은 파일에 상위 파일이있는 경우에만 작동합니다 (예 : 상위 파일 생성자 중 하나를 통해 생성됨 File). getParentFile()null 일 를 사용 lastIndexOf하거나 Apache CommonsFileNameUtils.getFullPath() 와 같은 것을 사용해야합니다 .

FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
=> C:/aaa/bbb/ccc/ddd

접두사 및 후행 구분 기호를 유지 / 삭제하는 몇 가지 변형이 있습니다. 동일한 FilenameUtils클래스를 사용하여 결과에서 이름을 가져 오거나 를 사용할 수 있습니다 lastIndexOf.


File f = new File("C:/aaa/bbb/ccc/ddd/test.java");
System.out.println(f.getParentFile().getName())

f.getParentFile() null 일 수 있으므로 확인해야합니다.


아래 사용,

File file = new File("file/path");
String parentPath = file.getAbsoluteFile().getParent();

Java 7에는 새로운 Paths api가 있습니다. 가장 현대적이고 깨끗한 솔루션은 다음과 같습니다.

Paths.get("C:/aaa/bbb/ccc/ddd/test.java").getParent().getFileName();

결과는 다음과 같습니다.

C:/aaa/bbb/ccc/ddd

String 경로 만 있고 새 File 객체를 만들고 싶지 않은 경우 다음과 같이 사용할 수 있습니다.

public static String getParentDirPath(String fileOrDirPath) {
    boolean endsWithSlash = fileOrDirPath.endsWith(File.separator);
    return fileOrDirPath.substring(0, fileOrDirPath.lastIndexOf(File.separatorChar, 
            endsWithSlash ? fileOrDirPath.length() - 2 : fileOrDirPath.length() - 1));
}

File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
File curentPath = new File(file.getParent());
//get current path "C:/aaa/bbb/ccc/ddd/"
String currentFolder= currentPath.getName().toString();
//get name of file to string "ddd"

다른 경로를 사용하여 "ddd"폴더를 추가해야하는 경우;

String currentFolder= "/" + currentPath.getName().toString();

Java 7부터 Path를 사용하는 것을 선호합니다. 경로를 다음 위치에만 입력하면됩니다.

Path dddDirectoryPath = Paths.get("C:/aaa/bbb/ccc/ddd/test.java");

get 메서드를 만듭니다.

public String getLastDirectoryName(Path directoryPath) {
   int nameCount = directoryPath.getNameCount();
   return directoryPath.getName(nameCount - 1);
}

Groovy에서 :

Filegroovy에서 문자열을 구문 분석 하기 위해 인스턴스 를 만들 필요가 없습니다 . 다음과 같이 수행 할 수 있습니다.

String path = "C:/aaa/bbb/ccc/ddd/test.java"
path.split('/')[-2]  // this will return ddd

분할은 배열을 생성 [C:, aaa, bbb, ccc, ddd, test.java]하고 인덱스 -2는 마지막 항목 이전의 항목을 가리 킵니다.이 경우에는ddd


    //get the parentfolder name
    File file = new File( System.getProperty("user.dir") + "/.");
    String parentPath = file.getParentFile().getName();

참고 URL : https://stackoverflow.com/questions/8197049/how-to-get-just-the-parent-directory-name-of-a-specific-file

반응형