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)