자바에서 파일을 읽는 파일, 그리고 상대적인 경로에 대한 문제

2853 단어 javaFile경로
1. 자바 프로젝트의 파일 읽기
1. System 또는 시스템의 Properties 객체 사용
① 직접적으로 String을 사용하여 상대적으로 Path = System.getProperty("user.dir");
② Properties 객체 사용
먼저 시스템의 속성을 훑어보겠습니다.

Properties properties = System.getProperties();
Enumeration pnames = properties.propertyNames();
while (pnames.hasMoreElements()) {
String pname = (String) pnames.nextElement();
System.out.print(pname + "--------------");
System.out.println(properties.getProperty(pname));
}
이것은 시스템의 속성입니다. 이로부터 사실은user를 사용합니다.dir 속성은 현재 프로젝트의 진짜 경로를 가져옵니다.
String을 통해 상대적으로 Path = 속성.getProperty("user.dir"); 얻다
내 컴퓨터 위의 프로젝트 Log4jProj의 진짜 경로는 다음과 같다.
user.dir--------------D:\Develop\workspace\ws_self\10_ws_eclipse_j2ee_mars\Log4jProj
사실 방식 ① 과 방식 ② 는 한 가지 뜻 으로 서로 다른 길 로 돌아간다
2, 두 번째 방법: 현재 클래스의 클래스 로더를 사용하여 ClassLoader 가져오기
먼저 Class 바이트 코드의 실례를 어떻게 얻는지 세 가지 방식을 살펴보자. (예를 들어 내 클래스는 데모)
① Demo.class
② Class.forName("클래스의 전체 이름")
③ Demo의 인스턴스 객체를 사용하여 객체의 getClass() 방법을 호출하여 해당 객체의 Class 인스턴스를 가져옵니다.
ClassLoader 객체를 가져오는 방법에 대한 Class 바이트 코드 인스턴스를 검토한 후
① Demo.class.getClassLoader()
② Class.forName("클래스의 전체 이름").getClassLoader()
③ 데모를 데모의 실례화된 객체로 가정합니다.getClass().getClassLoader()
④ Thread 객체의 getContextClassLoader() 메서드를 통해 가져오기
Thread.currentThread().getContextClassLoader()
본론으로 들어가기:
ClassLoader 대상이 생기면, 우리는 이때 ClassLoader 대상을 통해 자바 프로젝트의 파일을 가져옵니다.
우선 저의 현재 프로젝트 디렉터리 구조를 보여드릴게요.
실제 파일의 디렉터리 구조
이 경우 Test에서 log4j를 읽어야 합니다.properties 파일의 경로
ClassLoader를 사용하는 두 가지 방법 중 하나는 정적 인 비정적 인
출력 결과:
기억하세요. 여기 getSystemResource 방법은 URL 대상을 가져옵니다. getPath () 방법으로 경로를 가져와야 합니다.
1、log4j만 가져오면 됩니다.properties 파일의 입력 흐름은 다음과 같은 두 가지 방식을 통해
① 여전히 ClassLoader를 사용하는데 두 가지 방법이 있는데 하나는 정태적이고 하나는 비정태적이다

ClassLoader.getSystemResourceAsStream("config/log4j.properties");

Thread.currentThread().getContextClassLoader().getResourceAsStream("config/log4j.properties");
② File 파일로 포장한 다음 입력 스트림을 새로 만듭니다.

File file01 = new File("config/log4j.properties");
System.out.println(file01.getAbsolutePath());

File file02 = new File(properties.getProperty("user.dir") + "/bin/config/log4j.properties");
System.out.println(file02.getAbsolutePath());

//ClassLoader.getSystemResource URL 
File file03 = new File(ClassLoader.getSystemResource("config/log4j.properties").getPath());
System.out.println(file03.getAbsolutePath());
getSystemResource 방법이 파일을 가져오지 못하면
URL 객체가 null이고 getPath () 를 호출하면 오류가 발생합니다.
파일 대상이 있으면 흐름을 직접 만들 수 있습니다.
상기 자바에서 파일의 읽기 파일, 그리고 상대적인 경로에 대한 문제는 바로 편집자가 여러분에게 공유한 모든 내용입니다. 여러분께 참고가 되고 저희를 많이 사랑해 주시기 바랍니다.

좋은 웹페이지 즐겨찾기