>  기사  >  Java  >  Java에서 파일 경로를 작성하는 방법

Java에서 파일 경로를 작성하는 방법

angryTom
angryTom원래의
2019-11-12 10:38:242938검색

Java에서 파일 경로를 작성하는 방법

자바에서 파일을 가져올 경로를 작성하는 방법

#🎜🎜 #업로드 중입니다. 파일 및 파일 처리 시 리소스 파일의 경로를 얻어야 합니다. 그러나 개발 프로젝트에서 얻은 경로가 jar 패키지를 만든 후의 경로와 일치하지 않기 때문에 프로젝트에서 얻은 파일 경로가 우리가 원하는 파일 경로가 아닐 수도 있습니다. (추천 튜토리얼:

java tutorial)

1 리소스 경로 가져오기

String filePath = this.getClass().getResource("").getPath();
System.out.println("filePath: " + filePath);

at 프로젝트 개발에 표시된 경로:

filePath: /home/idea/project/java_basic/selfimpr-fileupload/target/classes/com/selfimpr/fileupload/controller/

프로젝트 jar 패키지의 경로:

 filePath: file:/home/idea/project/java_basic/selfimpr-fileupload/target/selfimpr-fileupload-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/com/selfimpr/fileupload/controller/

2 프로젝트 파일 컴파일 경로 가져오기#🎜🎜 #

String filePath = this.getClass().getResource("/").getPath();
System.out.println("filePath: " + filePath);
프로젝트 개발에 표시된 경로:

filePath: file:/home/idea/project/java_basic/selfimpr-fileupload/target/classes/

프로젝트 jar 패키지의 경로:

filePath: file:/home/idea/project/java_basic/selfimpr-fileupload/target/selfimpr-fileupload-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/

# 🎜 🎜#3. 프로젝트 루트 경로 가져오기(1)

File files = new File("");
String filePath = files.getCanonicalPath();
System.out.println("filePath: " + filePath);
프로젝트 개발에 표시된 경로:
filePath: /home/idea/project/java_basic

프로젝트 jar 패키지 경로: # 🎜🎜#

filePath: /home/idea/project/java_basic/selfimpr-fileupload/target

4. 프로젝트 루트 경로 가져오기(2)

String filePath = System.getProperty("user.dir");
System.out.println("filePath: " + filePath);

프로젝트 개발 중에 표시되는 경로: # 🎜🎜# filePath: /home/idea/project/java_basic프로젝트 jar 패키지의 경로:

filePath: /home/idea/project/java_basic/ selfimpr-fileupload /target


5. 개발 환경과 jar 환경 모두 사용 가능

/*  此方法,传入参数为String,不能带/  */
resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("/templates" + url);
/*  此方法,传入参数为String,不能带/  */
resourceAsStream = this.getClass().getResourceAsStream("/templates" + url);

컴파일과 상관없이 이 방법으로 얻은 프로젝트 경로 이 기간에는 jar 패키지 환경에서도 리소스 경로 아래의 파일을 얻을 수 있습니다.

위 내용은 Java에서 파일 경로를 작성하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.