Java의 클래스 경로에서 텍스트 파일을 실제로 읽는 방법
CLASSPATH 시스템 변수에 설정된 텍스트 파일을 읽으려고 합니다.사용자 변수가 아닙니다.
아래와 같이 파일에 입력 스트림을 가져오려고 합니다.
합니다(「파일D:\myDir
CLASSPATH를 사용하다
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("/SomeTextFile.txt");
InputStream in = this.getClass().getClassLoader().getResourceAsStream("//SomeTextFile.txt");
풀 합니다( 「」 「」 「」).D:\myDir\SomeTextFile.txt
CLASSPATH, 3은 CLASSPATH입니다.
하지 않고, ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」null
InputStream으로 됩니다.in
.
classpath 상의 디렉토리에서는 같은 classloader에 의해 로드된 클래스에서 다음 중 하나를 사용할 수 있습니다.
// From ClassLoader, all paths are "absolute" already - there's no context
// from which they could be relative. Therefore you don't need a leading slash.
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
만약 그것들이 효과가 없다면, 그것은 다른 무언가가 잘못되었다는 것을 의미한다.
예를 들어 다음 코드를 예로 들 수 있습니다.
package dummy;
import java.io.*;
public class Test
{
public static void main(String[] args)
{
InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt");
System.out.println(stream != null);
stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt");
System.out.println(stream != null);
}
}
이 디렉토리 구조는 다음과 같습니다.
code
dummy
Test.class
txt
SomeTextFile.txt
그런 다음(Linux 상자에 있는 것처럼 Unix 경로 구분자를 사용):
java -classpath code:txt dummy.Test
결과:
true
true
Spring Framework를 사용하는 경우(유틸리티 또는 컨테이너 모음으로 사용 - 후자의 기능을 사용할 필요가 없음) 리소스 추상화를 쉽게 사용할 수 있습니다.
Resource resource = new ClassPathResource("com/example/Foo.class");
리소스 인터페이스를 통해 리소스에 InputStream, URL, URI 또는 File로 액세스할 수 있습니다.예를 들어 파일 시스템 리소스로 리소스 유형을 변경하는 것은 인스턴스를 변경하는 간단한 문제입니다.
Java 7 NIO를 사용하여 클래스 패스에 있는 텍스트파일의 모든 행을 다음과 같이 읽습니다.
...
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
...
Files.readAllLines(
Paths.get(this.getClass().getResource("res.txt").toURI()), Charset.defaultCharset());
주의: 이것은 어떻게 할 수 있는가에 대한 예시입니다.필요에 따라 개선해야 합니다.이 예는 파일이 클래스 경로에 실제로 존재하는 경우에만 작동합니다.그렇지 않으면 Null Pointer가 됩니다.getResource()가 null을 반환하고 해당 null에서 .toURI()가 호출되면 예외가 느려집니다.
또한7 문자 중 는 "Java 7"에서 정의된 입니다.java.nio.charset.StandardCharsets
(이것들은 javadocs에 따르면 "Java 플랫폼의 모든 구현에서 사용할 수 있도록 보장"되어 있습니다.
따라서되는 있는 는, 으로 charset 「UTF-8」을합니다.StandardCharsets.UTF_8
시도해 보세요
InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");
클래스에 대한 클래스 로더만 클래스 경로에서 로드할 수 있기 때문에 시도가 실패했습니다.Java 시스템 자체에 클래스 로더를 사용했습니다.
실제로 파일 내용을 읽기 위해서는 Commons IO + Spring Core를 사용하는 것이 좋습니다.Java 8을 전제로 합니다.
try (InputStream stream = new ClassPathResource("package/resource").getInputStream()) {
IOUtils.toString(stream);
}
대체 방법:
InputStream stream = null;
try {
stream = new ClassPathResource("/log4j.xml").getInputStream();
IOUtils.toString(stream);
} finally {
IOUtils.closeQuietly(stream);
}
클래스의 절대 패스를 취득하려면 , 다음의 순서에 따릅니다.
String url = this.getClass().getResource("").getPath();
어찌된 일인지 내게는 최선의 답이 통하지 않는다.대신 조금 다른 코드를 사용해야 합니다.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("SomeTextFile.txt");
저는 이것이 같은 문제를 겪는 사람들에게 도움이 되기를 바랍니다.
Guava를 사용하는 경우:
import com.google.common.io.Resources;
CLASSPATH에서 URL을 얻을 수 있습니다.
URL resource = Resources.getResource("test.txt");
String file = resource.getFile(); // get file path
또는 InputStream:
InputStream is = Resources.getResource("test.txt").openStream();
classpath
, 쓸 수 있어요
private String resourceToString(String filePath) throws IOException, URISyntaxException
{
try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath))
{
return IOUtils.toString(inputStream);
}
}
IOUtils
는 의 일부입니다.
이렇게 불러주세요.
String fileContents = resourceToString("ImOnTheClasspath.txt");
CLASSPATH 시스템 변수에 설정된 텍스트 파일을 읽으려고 합니다.라고 말합니다.이 대화 상자는 Windows에서 "시스템 변수"를 편집하기 위해 이 보기 흉한 대화 상자를 사용하고 있는 것 같습니다.
이제 콘솔에서 Java 프로그램을 실행합니다.그리고 그것은 효과가 없습니다.콘솔은 시작할 때 시스템 변수 값의 복사본을 가져옵니다.즉, 이후 대화상자의 변경은 아무런 영향을 미치지 않습니다.
다음과 같은 솔루션이 있습니다.
변경할 때마다 새 콘솔 시작
set CLASSPATH=...
콘솔에서 변수 복사본을 설정하고 코드가 작동하면 마지막 값을 변수 대화상자에 붙여넣습니다.콜을 Java에 .
.BAT
파일을 입력하고 더블 클릭합니다.이렇게 하면 매번 새 콘솔이 생성됩니다(따라서 시스템 변수의 현재 값이 복사됩니다).
: 사용자 변수:CLASSPATH
이치노 Java 콜은 보통 ..BAT
를 를합니다(classpath 를 합니다.set CLASSPATH=
글로벌 시스템 또는 사용자 변수에 의존하지 마십시오.
또한 여러 Java 프로그램이 서로 다른 클래스 경로를 가질 수밖에 없기 때문에 컴퓨터에서 여러 Java 프로그램을 사용할 수 있습니다.
내 대답은 질문에 있는 그대로가 아니다.프로젝트 클래스 경로에서 Java 애플리케이션으로 파일을 얼마나 쉽게 읽을 수 있는지 솔루션을 제공하고 있습니다.
예를 들어 설정 파일명 example.xml이 다음과 같은 경로에 있다고 가정합니다.
com.myproject.config.dev
Java 실행 클래스 파일은 다음 경로에 있습니다.-
com.my project.server.main
이제 위의 경로에서 dev와 main directory/folder(com.myproject)에 액세스할 수 있는 가장 가까운 공통 디렉토리/폴더를 확인하세요.server.main - 어플리케이션의 Java 실행 가능 클래스가 존재하는 곳)– example.xml 파일에 액세스할 수 있는 가장 가까운 공통 디렉토리/폴더인 myproject 폴더/디렉토리임을 알 수 있습니다.따라서 java 실행 가능 클래스는 폴더/디렉토리 메인에 존재하기 때문에 내 프로젝트에 액세스하려면 ../../와 같은 두 단계로 돌아가야 합니다.다음에, 파일을 읽는 방법에 대해 설명합니다.-
package com.myproject.server.main;
class Example {
File xmlFile;
public Example(){
String filePath = this.getClass().getResource("../../config/dev/example.xml").getPath();
this.xmlFile = new File(filePath);
}
public File getXMLFile() {
return this.xmlFile;
}
public static void main(String args[]){
Example ex = new Example();
File xmlFile = ex.getXMLFile();
}
}
프로젝트를 jar 파일로 컴파일하는 경우: 파일을 resources/files/your_file.text 또는 pdf에 저장할 수 있습니다.
다음 코드를 사용합니다.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class readFileService(){
private static final Logger LOGGER = LoggerFactory.getLogger(readFileService.class);
public byte[] getFile(){
String filePath="/files/your_file";
InputStream inputStreamFile;
byte[] bytes;
try{
inputStreamFile = this.getClass().getResourceAsStream(filePath);
bytes = new byte[inputStreamFile.available()];
inputStreamFile.read(bytes);
} catch(NullPointerException | IOException e) {
LOGGER.error("Erreur read file "+filePath+" error message :" +e.getMessage());
return null;
}
return bytes;
}
}
저는 webshpere 어플리케이션 서버를 사용하고 있으며 웹 모듈은 Spring MVC에 구축되어 있습니다.그Test.properties
리소스 폴더에 있는 다음 파일을 로드하려고 했습니다.
this.getClass().getClassLoader().getResourceAsStream("Test.properties");
this.getClass().getResourceAsStream("/Test.properties");
위의 코드 중 어느 것도 파일을 로드하지 않았습니다.
그러나 아래 코드의 도움으로 속성 파일이 성공적으로 로드되었습니다.
Thread.currentThread().getContextClassLoader().getResourceAsStream("Test.properties");
사용자 "user1695166" 덕분입니다.
사용하다org.apache.commons.io.FileUtils.readFileToString(new File("src/test/resources/sample-data/fileName.txt"));
getClassLoader() 메서드를 사용하지 말고 파일 이름 앞에 "/"를 사용합니다."/"는 매우 중요합니다.
this.getClass().getResourceAsStream("/SomeTextFile.txt");
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile
{
/**
* * feel free to make any modification I have have been here so I feel you
* * * @param args * @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// thread pool of 10
File dir = new File(".");
// read file from same directory as source //
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
// if you wanna read file name with txt files
if (file.getName().contains("txt")) {
System.out.println(file.getName());
}
// if you want to open text file and read each line then
if (file.getName().contains("txt")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(
file.getAbsolutePath());
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(
fileReader);
String line;
// get file details and get info you need.
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// here you can say...
// System.out.println(line.substring(0, 10)); this
// prints from 0 to 10 indext
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '"
+ file.getName() + "'");
} catch (IOException ex) {
System.out.println("Error reading file '"
+ file.getName() + "'");
// Or we could just do this:
ex.printStackTrace();
}
}
}
}
}
}
java classpath에 system variable을 배치해야 합니다.
언급URL : https://stackoverflow.com/questions/1464291/how-to-really-read-text-file-from-classpath-in-java
'programing' 카테고리의 다른 글
VSCode에서 Vuex Getter Setter를 생성하는 방법 (0) | 2022.07.21 |
---|---|
Vuej 2 + 폼 검증 (0) | 2022.07.21 |
Vuex - 전체 어레이 업데이트 (0) | 2022.07.21 |
C 경고 함수의 암시적 선언 '종료' (0) | 2022.07.21 |
스플라이싱 어레이가 테이블 행 Vuej를 다시 렌더링하지 않음 (0) | 2022.07.21 |