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 Test
이 출력 current dir = /User/me
됩니다.
좋은 객체 지향 명령 줄 인수 파서를 사용하는 것도 보너스로 봐야합니다. Java Simple Argument Parser 인 JSAP을 적극 권장 합니다. 이를 System.getProperty("user.dir")
통해 동작을 재정의하기 위해 다른 것을 사용 하거나 다른 방법으로 전달할 수 있습니다. 훨씬 더 유지 보수가 쉬운 솔루션. 이렇게하면 디렉토리로 전달하기가 매우 쉬워지고 user.dir
아무것도 전달되지 않으면 다시 넘어갈 수 있습니다.
사용하십시오 CodeSource#getLocation()
. 이것은 JAR 파일에서도 잘 작동합니다. 당신은 얻을 수 CodeSource
로 ProtectionDomain#getCodeSource()
하고, ProtectionDomain
차례로 얻을 수 있습니다 Class#getProtectionDomain()
.
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()
방금 사용했습니다 :
import java.nio.file.Path;
import java.nio.file.Paths;
...
Path workingDirectory=Paths.get(".").toAbsolutePath();
현재 소스 코드의 절대 경로를 원한다면 제 제안은 다음과 같습니다.
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));
메인 클래스가 로컬 하드 디스크의 파일에 있다고 누가 말합니까? 클래스는 종종 JAR 파일에 번들로 묶여 있으며 때로는 네트워크를 통해로드되거나 심지어는 즉시 생성되기도합니다.
So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.
If you want to get your current working directory then use the following line
System.out.println(new File("").getAbsolutePath());
참고URL : https://stackoverflow.com/questions/3153337/how-to-get-current-working-directory-in-java
'programing tip' 카테고리의 다른 글
로드 콜백 후 jQuery UI 대화 상자 제목 변경 (0) | 2020.08.03 |
---|---|
Vagrant Cache에서 vms 목록 제거 (0) | 2020.08.03 |
Foundation에서 요일을 어떻게 알 수 있습니까? (0) | 2020.08.03 |
reactjs 앱에 부트 스트랩 CSS와 JS를 포함시키는 방법은 무엇입니까? (0) | 2020.08.03 |
HTTP를 통해 안전하게 비밀번호를 보내는 방법은 무엇입니까? (0) | 2020.08.02 |