source

Java에서 현재 작업 디렉토리를 가져오려면 어떻게 해야 합니까?

bestscript 2022. 11. 24. 23:40

Java에서 현재 작업 디렉토리를 가져오려면 어떻게 해야 합니까?

예를 들어 메인 수업이 있다고 칩시다.C:\Users\Justian\Documents\. 프로그램이 에 있음을 나타내려면 어떻게 해야 합니까?C:\Users\Justian\Documents?

하드 코딩은 옵션이 아닙니다.다른 곳으로 이동하는 경우 적응할 수 있어야 합니다.

폴더에 CSV 파일을 많이 덤프하여 프로그램이 모든 파일을 인식하게 하고 데이터를 로드하여 조작하고 싶습니다.그 폴더를 탐색하는 방법을 알고 싶을 뿐입니다.

가지 방법은 시스템 속성을 사용하는 것입니다. System.getProperty("user.dir");그러면 "속성이 초기화되었을 때 현재 작업 디렉토리"가 나타납니다.아마 이게 네가 원하는 것일 거야java실제 .jar 파일이 머신상의 다른 장소에 있는 경우에도 처리할 파일이 있는 디렉토리에서 명령어가 발행되었습니다.대부분의 경우 실제 .jar 파일의 디렉토리는 그다지 유용하지 않습니다.

다음은 .class 파일이 있는 .class 파일 또는 .jar 파일의 위치에 관계없이 명령어가 호출된 현재 디렉토리를 출력합니다.

public class Test
{
    public static void main(final String[] args)
    {
        final String dir = System.getProperty("user.dir");
        System.out.println("current dir = " + dir);
    }
}  

에 있으면/User/me/위의 코드를 포함한 .jar 파일은/opt/some/nested/dir/지휘부java -jar /opt/some/nested/dir/test.jar Testwill 출력current dir = /User/me.

또한 적절한 객체 지향 명령줄 인수 구문 분석기를 사용하는 것도 고려해야 합니다.Java Simple Argument 파서인 JSAP을 적극 추천합니다.이렇게 하면System.getProperty("user.dir")아니면 다른 것을 넘겨서 행동을 무시하도록 하는 거죠유지보수가 용이한 솔루션.이것에 의해, 디렉토리에서의 처리가 매우 간단하게 되어, 에 폴백 할 수 있게 됩니다.user.dir아무 것도 전달되지 않았다면요.

사용. 이것은 JAR 파일에서도 정상적으로 동작합니다.입수할 수 있다CodeSourceby와 by theProtectionDomain를 통해 얻을 수 있습니다.

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}

OP 설명에 따라 업데이트:

폴더에 CSV 파일을 많이 덤프하여 프로그램이 모든 파일을 인식하게 하고 데이터를 로드하여 조작하고 싶습니다.그 폴더를 탐색하는 방법을 알고 싶을 뿐입니다.

그러기 위해서는 프로그램 내의 상대 경로를 하드코딩/알아야 합니다.사용할 수 있도록 클래스 경로에 경로를 추가하는 것이 좋습니다.ClassLoader#getResource()

File classpathRoot = new File(classLoader.getResource("").getPath());
File[] csvFiles = classpathRoot.listFiles(new FilenameFilter() {
    @Override public boolean accept(File dir, String name) {
        return name.endsWith(".csv");
    }
});

를 「」로서 .main()★★★★★★ 。

File currentDirectory = new File(new File(".").getAbsolutePath());
System.out.println(currentDirectory.getCanonicalPath());
System.out.println(currentDirectory.getAbsolutePath());

다음과 같이 인쇄합니다.

/path/to/current/directory
/path/to/current/directory/.

:File.getCanonicalPath()만 IOException은 한다.../../../

this.getClass().getClassLoader().getResource("").getPath()

현재 작업 디렉토리를 가져오려면 다음 행을 사용하십시오.

System.out.println(new File("").getAbsolutePath());

현재 소스 코드의 절대 경로를 원하는 경우 제안할 사항은 다음과 같습니다.

String internalPath = this.getClass().getName().replace(".", File.separator);
String externalPath = System.getProperty("user.dir")+File.separator+"src";
String workDir = externalPath+File.separator+internalPath.substring(0, internalPath.lastIndexOf(File.separator));

사용했을 뿐:

import java.nio.file.Path;
import java.nio.file.Paths;

...

Path workingDirectory=Paths.get(".").toAbsolutePath();

누가 메인 클래스가 로컬 하드디스크에 있는 파일에 있다고 하던가요?클래스는 JAR 파일 내에 번들되는 경우가 많고 네트워크를 통해 로드되거나 즉시 생성되기도 합니다.

그래서 정말 하고 싶은 게 뭐야?수업의 출처를 추측하지 않고 할 수 있는 방법이 있을 것이다.

언급URL : https://stackoverflow.com/questions/3153337/how-to-get-current-working-directory-in-java