리소스 폴더에서 파일을 로드하는 방법
내 프로젝트의 구조는 다음과 같다.
/src/main/java/
/src/main/resources/
/src/test/java/
/src/test/resources/
나는 안에 파일이 있다./src/test/resources/test.csv
그리고 나는 다음에 있는 유닛 테스트에서 파일을 로드하고 싶다./src/test/java/MyTest.java
나는 작동하지 않는 이 코드를 가지고 있다.그것은 "그런 파일이나 디렉토리가 없다"고 불평한다.
BufferedReader br = new BufferedReader (new FileReader(test.csv))
나도 이거 해봤어.
InputStream is = (InputStream) MyTest.class.getResourcesAsStream(test.csv))
이것 또한 효과가 없다.돌아온다.null
나는 내 프로젝트를 만들기 위해 메이븐을 사용하고 있다.
다음을 시도해 보십시오.
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("test.csv");
위의 내용이 통하지 않으면 다음과 같은 등급의 다양한 프로젝트가 추가되었다: (여기서 코드).2
이 클래스가 사용되는 몇 가지 예는 다음과 같다.
src\main\main\com\company\test\\YourCallingClass.javasrc\main\java\com\opensimphony\xwork2\util\ClassLoaderUtil.javasrc\main\main\test.properties.
// java.net.URL
URL url = ClassLoaderUtil.getResource("test.csv", YourCallingClass.class);
Path path = Paths.get(url.toURI());
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// java.io.InputStream
InputStream inputStream = ClassLoaderUtil.getResourceAsStream("test.csv", YourCallingClass.class);
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
for (String line; (line = reader.readLine()) != null;) {
// Process line
}
메모들
시도:
InputStream is = MyTest.class.getResourceAsStream("/test.csv");
IERCgetResourceAsStream()
기본적으로 클래스의 패키지에 상대적이다.
@Terran이 지적한 바와 같이, 잊지 말고 그 내용을 추가하라./
이름의 에서.
스프링 프로젝트에서 다음 코드 시도
ClassPathResource resource = new ClassPathResource("fileName");
InputStream inputStream = resource.getInputStream();
또는 봄 이외의 프로젝트에서
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());
InputStream inputStream = new FileInputStream(file);
구아바를 이용한 빠른 해결책은 다음과 같다.
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
public String readResource(final String fileName, Charset charset) throws IOException {
return Resources.toString(Resources.getResource(fileName), charset);
}
사용량:
String fixture = this.readResource("filename.txt", Charsets.UTF_8)
비 스프링 프로젝트:
String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();
Stream<String> lines = Files.lines(Paths.get(filePath));
아니면
String filePath = Objects.requireNonNull(getClass().getClassLoader().getResource("any.json")).getPath();
InputStream in = new FileInputStream(filePath);
스프링 프로젝트의 경우 한 줄 코드를 사용하여 리소스 폴더 아래의 파일을 가져올 수도 있다.
File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "any.json");
String content = new String(Files.readAllBytes(file.toPath()));
1.7 이후 자바의 경우
List<String> lines = Files.readAllLines(Paths.get(getClass().getResource("test.csv").toURI()));
또는 Spring ech시스템에 있는 경우 Spring utils를 사용할 수 있다.
final val file = ResourceUtils.getFile("classpath:json/abcd.json");
자세한 내용은 다음 블로그를 참조하십시오.
https://todzhang.com/blogs/tech/en/save_resources_to_files
이 파일은 클래스 로더에 의해 발견되지 않았으며, 이는 이 파일이 공예품(jar)에 포장되지 않았다는 것을 의미한다.너는 그 프로젝트를 만들어야 해.예를 들어, maven:
mvn clean package
따라서 리소스 폴더에 추가한 파일은 manven 빌드에 들어가 응용 프로그램에서 사용할 수 있게 된다.
나는 내 대답을 지키고 싶다: 그것은 파일을 읽는 방법을 설명하지 않는다. 그것은 그 이유를 설명한다. InputStream
또는resource
무효였다.비슷한 대답이 여기 있다.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream("test.csv");
컨텍스트 ClassLoader를 사용하여 리소스를 찾으면 애플리케이션 성능이 저하될 것이 분명하다.
지금 나는 maven이 만든 자원 디렉토리에서 글꼴을 읽기 위한 소스 코드를 설명하고 있다.
스크래/메인/스스로/스스로릴.ttf
Font getCalibriLightFont(int fontSize){
Font font = null;
try{
URL fontURL = OneMethod.class.getResource("/calibril.ttf");
InputStream fontStream = fontURL.openStream();
font = new Font(Font.createFont(Font.TRUETYPE_FONT, fontStream).getFamily(), Font.PLAIN, fontSize);
fontStream.close();
}catch(IOException | FontFormatException ief){
font = new Font("Arial", Font.PLAIN, fontSize);
ief.printStackTrace();
}
return font;
}
나에게도 효과가 있었고, 전체 소스 코드가 당신에게도 도움이 되길 바라, 즐기세요!
다음을 가져오십시오.
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.ArrayList;
다음 메서드는 ArrayList of Strings에 있는 파일을 반환한다.
public ArrayList<String> loadFile(String filename){
ArrayList<String> lines = new ArrayList<String>();
try{
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classloader.getResourceAsStream(filename);
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader);
for (String line; (line = reader.readLine()) != null;) {
lines.add(line);
}
}catch(FileNotFoundException fnfe){
// process errors
}catch(IOException ioe){
// process errors
}
return lines;
}
getResource()는 다음 위치에 있는 리소스 파일을 사용하여 정상적으로 작동하고 있었다.src/main/resources
지만 . 다른 경로에 있는 파일을 가져오는 것src/main/resources
라고 말하다src/test/java
열심히 만들어야 한다.
다음 예시는 당신을 도울 수 있다.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
public class Main {
public static void main(String[] args) throws URISyntaxException, IOException {
URL location = Main.class.getProtectionDomain().getCodeSource().getLocation();
BufferedReader br = new BufferedReader(new FileReader(location.getPath().toString().replace("/target/classes/", "/src/test/java/youfilename.txt")));
}
}
당신은 com.google.common.io을 사용할 수 있다.Resources.getResource가 파일의 URL을 읽은 다음 java.nio.file을 사용하여 파일 콘텐츠를 가져오도록 하십시오.파일 내용을 읽을 파일.
URL urlPath = Resources.getResource("src/main/resource");
List<String> multilineContent= Files.readAllLines(Paths.get(urlPath.toURI()));
만약 당신이 정적 방법으로 파일을 로드한다면,ClassLoader classLoader = getClass().getClassLoader();
이것은 당신에게 오류를 줄 수 있다.
이 예를 들어, 리소스로부터 로드하고자 하는 파일이 리소스 >> 이미지 >> 테스트.gif
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
Resource resource = new ClassPathResource("Images/Test.gif");
File file = resource.getFile();
src/리소스 폴더에서 파일을 읽으려면 다음을 수행하십시오.
DataSource fds = new FileDataSource(getFileHandle("images/sample.jpeg"));
public static File getFileHandle(String fileName){
return new File(YourClassName.class.getClassLoader().getResource(fileName).getFile());
}
정적 참조가 아닌 경우:
return new File(getClass().getClassLoader().getResource(fileName).getFile());
Maven-build jar를 실행하지 않을 때(예: IDE에서 실행될 때) 코드가 작동하시겠습니까?그렇다면 파일이 항아리에 실제로 포함되어 있는지 확인하십시오.리소스 폴더는 다음 위치에 있는 pom 파일에 포함되어야 한다.<build><resources>
.
다음 클래스를 사용하여 a를 로드할 수 있음resource
처음부터classpath
또한 주어진 에러에 문제가 있을 경우 적합한 에러 메시지를 받는다.filePath
.
import java.io.InputStream;
import java.nio.file.NoSuchFileException;
public class ResourceLoader
{
private String filePath;
public ResourceLoader(String filePath)
{
this.filePath = filePath;
if(filePath.startsWith("/"))
{
throw new IllegalArgumentException("Relative paths may not have a leading slash!");
}
}
public InputStream getResource() throws NoSuchFileException
{
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(filePath);
if(inputStream == null)
{
throw new NoSuchFileException("Resource file not found. Note that the current directory is the source folder!");
}
return inputStream;
}
}
this.getClass().getClassLoader().getResource("filename").getPath()
답안을 따라갔는데도 시험 폴더에 있는 내 파일을 찾을 수 없었다.그것은 그 프로젝트를 재건함으로써 해결되었다.IntelliJ는 새로운 파일을 자동으로 인식하지 못한 것 같다.알아내기엔 꽤 고약하군.
나는 실행 항아리 및 IDE에서 모두 작업할 수 있도록 작성했다.
InputStream schemaStream =
ProductUtil.class.getClassLoader().getResourceAsStream(jsonSchemaPath);
byte[] buffer = new byte[schemaStream.available()];
schemaStream.read(buffer);
File tempFile = File.createTempFile("com/package/schema/testSchema", "json");
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
out.write(buffer);
"클래스"나 "클래스 로더"에 대한 언급 없이 작동하게 한다.
파일의 위치를 '예'로 하는 세 가지 시나리오가 있다고 하자.file' 및 작업 디렉토리(앱 실행 위치)는 홈/마이문서/프로그램/프로그램/마이앱:
a)작업 디렉토리의 하위 폴더 하위 하위 폴더: myapp/res/file/예:파일
b)작업 디렉토리의 하위 폴더가 아닌 하위 폴더: 프로젝트/파일/예:파일
b2)작업 디렉토리의 하위 폴더가 아닌 다른 하위 폴더: 프로그램/파일/예:파일
c)루트 폴더: 홈/내 문서/파일/예:파일(Linux; Windows에서 home/을 C:로 대체)
1) 올바른 길찾기: a)String path = "res/files/example.file";
b)String path = "../projects/files/example.file"
b2)String path = "../../program/files/example.file"
c)String path = "/home/mydocuments/files/example.file"
기본적으로 루트 폴더인 경우 선행 슬래시로 경로 이름을 시작하십시오.하위 폴더인 경우 경로 이름 앞에 슬래시가 없어야 한다.하위 폴더가 작업 디렉토리의 하위 폴더가 아닌 경우, "../"를 사용하여 해당 폴더에 cd를 적용해야 한다.이것은 시스템이 하나의 폴더를 위로 올리도록 지시한다.
2) 올바른 경로를 통과하여 파일 객체 생성:
File file = new File(path);
3) 이제 가도 좋아:
BufferedReader br = new BufferedReader(new FileReader(file));
참조URL: https://stackoverflow.com/questions/15749192/how-do-i-load-a-file-from-resource-folder
'programing' 카테고리의 다른 글
부울 체크에 xor 연산자를 사용하는 것이 좋은 관행인가? (0) | 2022.05.23 |
---|---|
JNI 공유 라이브러리(JDK) 로드 실패 (0) | 2022.05.23 |
그러면 Vuex에서 getter가 있는 스토어 상태를 약속과 함께 가져올 수 없음 (0) | 2022.05.22 |
Vue/Nuxt 라이프사이클에서 사전 생성 및 생성된 Getter를 호출함 (0) | 2022.05.22 |
"어떤 용도로도 사용할 수 있도록 예약"의 의미는 무엇인가? (0) | 2022.05.22 |