Programing

Java 프로그램 실행 경로를 얻는 방법

lottogame 2020. 10. 9. 08:44
반응형

Java 프로그램 실행 경로를 얻는 방법


이 질문에 이미 답변이 있습니다.

실행중인 Java 프로그램의 기본 클래스 경로를 얻는 방법이 있습니까?

구조는

D:/
|---Project
       |------bin
       |------src

나는 경로를 D:\Project\bin\.

시도 System.getProperty("java.class.path");했지만 문제는 다음과 같이 실행하면

java -classpath D:\Project\bin;D:\Project\src\  Main

Output 
Getting : D:\Project\bin;D:\Project\src\
Want    : D:\Project\bin

이것을 할 방법이 있습니까?



===== 편집 =====

여기 해결책이 있습니다.

솔루션 1 ( Jon Skeet 작성 )

package foo;

public class Test
{
    public static void main(String[] args)
    {
        ClassLoader loader = Test.class.getClassLoader();
        System.out.println(loader.getResource("foo/Test.class"));
    }
}

이것은 다음과 같이 인쇄되었습니다.

file:/C:/Users/Jon/Test/foo/Test.class


솔루션 2 ( Erickson 작성 )

URL main = Main.class.getResource("Main.class");
if (!"file".equalsIgnoreCase(main.getProtocol()))
  throw new IllegalStateException("Main class is not stored in a file.");
File path = new File(main.getPath());

대부분의 클래스 파일은 JAR 파일로 어셈블되므로 모든 경우에 작동하지는 않습니다 (따라서 IllegalStateException). 그러나이 기술을 가진 클래스를 포함하는 JAR를 찾을 수 있습니다, 그리고 당신에게 전화를 대체하여 클래스 파일의 내용을 얻을 수있는 getResourceAsStream()대신에 getResource(), 그 클래스는 파일 시스템 또는 JAR에 있는지 여부를 작동합니다 .


이 코드를 시도하십시오.

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

' MyClass'를 기본 메서드가 포함 된 클래스로 바꿉니다.

또는 다음을 사용할 수도 있습니다.

System.getProperty("java.class.path")

위에서 언급 한 시스템 속성은

클래스 파일이 포함 된 디렉토리 및 JAR 아카이브를 찾는 데 사용되는 경로입니다. 클래스 경로의 요소는 path.separator 속성에 지정된 플랫폼 별 문자로 구분됩니다.


사용하다

System.getProperty("java.class.path")

참조 http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html를

You can also split it into it's elements easily

String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);

You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()


    ClassLoader cl = ClassLoader.getSystemClassLoader();

    URL[] urls = ((URLClassLoader)cl).getURLs();

    for(URL url: urls){
        System.out.println(url.getFile());
    }

참고URL : https://stackoverflow.com/questions/17540942/how-to-get-the-path-of-running-java-program

반응형