Java –リソースフォルダーからファイルを読み取る
このチュートリアルでは、ランタイム環境と単体テスト環境の両方で、resourcesフォルダーまたはクラスパスからファイルを読み取る方法を示します。 ファイルをsrc/main/resourcesフォルダーに入れて、次のコードスニペットでファイルを読み取ってみてください。
1. getResource
File file = new File(
getClass().getClassLoader().getResource("database.properties").getFile()
);
2. getResourceAsStream
InputStream inputStream = getClass()
.getClassLoader().getResourceAsStream("database.properties");
Note
このgetResourceAsStream
in static methodに興味があるかもしれません
1. プロジェクトディレクトリ
Mavenプロジェクトの構造を確認します。

2. リソースフォルダーからファイルを読み取る
src/main/resources/database.properties
datasource.url=jdbc:mysql://localhost/example?useSSL=false datasource.username=root datasource.password=password datasource.driver-class-name=com.mysql.jdbc.Driver
database.propertiesファイルを読み取り、内容を印刷します。
Application.java
package com.example;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
public class Application {
public static void main(String[] args) throws IOException {
Application main = new Application();
File file = main.getFileFromResources("database.properties");
printFile(file);
}
// get file from classpath, resources folder
private File getFileFromResources(String fileName) {
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file is not found!");
} else {
return new File(resource.getFile());
}
}
private static void printFile(File file) throws IOException {
if (file == null) return;
try (FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
}
出力
datasource.url=jdbc:mysql://localhost/example?useSSL=false datasource.username=root datasource.password=password datasource.driver-class-name=com.mysql.jdbc.Driver
3. 単体テスト
src/test/resources/xml/data.xml
100 example 99 example
data.xmlを読み取り、内容を印刷します。
ApplicationTest.java
package com.example;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class ApplicationTest {
@DisplayName("Test loading XML")
@Test
void loadXMLTest() {
ClassLoader classLoader = getClass().getClassLoader();
try (InputStream inputStream = classLoader.getResourceAsStream("xml/data.xml")) {
String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
出力
100 example 99 example
pom.xml
commons-io commons-io 2.6 org.junit.jupiter junit-jupiter 5.4.2 test
ソースコードをダウンロード
ダウンロード–java-get-file-from-resources.zip(6KB)