program tip

Java 프로젝트의 상대 경로에서 파일을 읽는 방법은 무엇입니까?

radiobox 2020. 8. 11. 08:16
반응형

Java 프로젝트의 상대 경로에서 파일을 읽는 방법은 무엇입니까? java.io.File이 지정된 경로를 찾을 수 없습니다.


2 개의 패키지가있는 프로젝트가 있습니다.

  1. tkorg.idrs.core.searchengines
  2. tkorg.idrs.core.searchengines

패키지 (2)에는 텍스트 파일이 ListStopWords.txt있고, 패키지 (1)에는 클래스가 FileLoadder있습니다. 다음은 코드입니다 FileLoader.

File file = new File("properties\\files\\ListStopWords.txt");

그러나 다음과 같은 오류가 있습니다.

The system cannot find the path specified

그것을 고칠 해결책을 줄 수 있습니까? 감사.


이미 클래스 경로에있는 경우 디스크 파일 시스템 대신 클래스 경로에서 가져옵니다. .NET에서 상대 경로를 조작하지 마십시오 java.io.File. Java 코드 내부에서 완전히 제어 할 수없는 현재 작업 디렉토리에 의존합니다.

클래스 ListStopWords.txt와 동일한 패키지에 있다고 가정하고 FileLoader다음을 수행하십시오.

URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());

또는 궁극적으로 추구하는 것이 실제로 그 InputStream하나 인 경우 :

InputStream input = getClass().getResourceAsStream("ListStopWords.txt");

는 디스크 파일 시스템 경로를 나타내지 않을 수도 있지만 가상 파일 시스템 경로를 나타낼 수도 new File()있기 때문에을 만드는 것보다 확실히 선호 url됩니다 (JAR가 디스크 파일 시스템의 임시 폴더가 아닌 메모리로 확장 될 때 발생할 수 있음). 또는 File생성자가 정의 할 수없는 네트워크 경로도 있습니다.

파일이-패키지 이름 힌트로서- 실제로 "잘못된"확장자를 가진 완전한 속성 파일 ( key=value포함 )이면 InputStream즉시 load()메소드에 공급할 수 있습니다.

Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));

참고 : static컨텍스트 내부 에서 액세스하려는 경우 위의 예 대신 FileLoader.class(또는 무엇이든 YourClass.class) 사용하십시오 getClass().


파일의 상대 경로를 지정하려는 경우 다음 행을 사용할 수 있습니다.

File file = new File("./properties/files/ListStopWords.txt");  

상대 경로는. 운영자.

  • . 현재 실행중인 컨텍스트와 동일한 폴더를 의미합니다.
  • ..은 현재 실행중인 컨텍스트의 상위 폴더를 의미합니다.

그래서 문제는 자바가 현재 찾고있는 경로를 어떻게 아는가?

작은 실험을하다

   File directory = new File("./");
   System.out.println(directory.getAbsolutePath());

출력을 관찰하면 Java가 찾고있는 현재 디렉토리를 알 수 있습니다. 거기에서 ./ 연산자를 사용하여 파일을 찾습니다.

예를 들어 출력이

G : \ JAVA8Ws \ MyProject \ content.

파일은 MyProject 폴더에 있습니다.

File resourceFile = new File("../myFile.txt");

도움이 되었기를 바랍니다


InputStream in = FileLoader.class.getResourceAsStream("<relative path from this class to the file to be read>");
try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
} catch (Exception e) {
    e.printStackTrace();
}

시험 .\properties\files\ListStopWords.txt


BalusC에서 제공하는 답변은이 경우에 작동하지만 파일 경로에 공백이 포함 된 경우 URL에서 유효한 파일 이름이 아닌 % 20으로 변환되기 때문에 중단됩니다. 문자열이 아닌 URI를 사용하여 File 객체를 생성하면 공백이 올바르게 처리됩니다.

URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());

나는 댓글을 달 수 있었지만 그에 대한 담당자가 적습니다. Samrat의 대답이 나를 위해 일했습니다. 다음 코드를 통해 현재 디렉토리 경로를 보는 것이 좋습니다.

    File directory = new File("./");
    System.out.println(directory.getAbsolutePath());

프로젝트에서 직면 한 문제를 바로 잡는 데 사용했습니다. ./를 사용하여 현재 디렉토리의 상위 디렉토리로 돌아 가야합니다.

    ./test/conf/appProperties/keystore 

src / main // js / Simulator.java 내부에서 'command.json'을 구문 분석하고 싶었습니다. 이를 위해 src 폴더에 json 파일을 복사하고 다음과 같은 절대 경로를 제공했습니다.

Object obj  = parser.parse(new FileReader("./src/command.json"));

enter image description here

클래스의 resources디렉토리에서 읽고 싶다고 가정합니다 FileSystem.

String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);

System.out.println(Files.readString(path));

Note: Leading . is not needed.


If you are trying to call getClass() from Static method or static block the you can do the following way.

You can call getClass() on the Properties object you are loading into.

public static Properties pathProperties = null;

static { 
    pathProperties = new Properties();
    String pathPropertiesFile = "/file.xml;
    InputStream paths = pathProperties.getClass().getResourceAsStream(pathPropertiesFile);
}

If text file is not being read, try using a more closer absolute path (if you wish you could use complete absolute path,) like this:

FileInputStream fin=new FileInputStream("\\Dash\\src\\RS\\Test.txt");

assume that the absolute path is:

C:\\Folder1\\Folder2\\Dash\\src\\RS\\Test.txt

참고URL : https://stackoverflow.com/questions/3844307/how-to-read-file-from-relative-path-in-java-project-java-io-file-cannot-find-th

반응형