摘要:在这篇文章中,我们将看到如何从java的resources文件夹中读取文件。如果您创建了maven项目(简单的java或动态web项目),您将看到文件夹src/jav/resources。您可以使用这些简单的代码从resources文件夹中读取数据。

// Getting ClassLoader obj
ClassLoader classLoader = this.getClass().getClassLoader();
// Getting resource(File) from class loader
File configFile = new File(classLoader.getResource(fileName).getFile());

项目结构

Read a file from resources folder in java_读取数据

Java Program:

package cn.micai.io;

import java.io.*;
import java.util.Properties;

/**
* 描述:How to read properties file in java
* <p>
*
* @author: 赵新国
* @date: 2018/6/7 13:25
*/
public class ReadPropertiesFileJavaMain {

public static void main(String [] args) throws IOException {

ReadPropertiesFileJavaMain rp = new ReadPropertiesFileJavaMain();
System.out.println("Reading file from resources folder");
System.out.println("-----------------------------");

rp.readFile("config.properties");

System.out.println("-----------------------------");


}

public void readFile(String fileName) {
FileInputStream fileInputStream = null;
try {
// Getting ClassLoader obj
ClassLoader classLoader = this.getClass().getClassLoader();
// Getting resource(File) from class loader
File configFile = new File(classLoader.getResource(fileName).getFile());

fileInputStream = new FileInputStream(configFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

当您运行在程序之上时,您将得到以下输出。

Read a file from resources folder in java_java_02