九种方式获取resources目录下文件的方式。其中打印文件的方法如下:
/**
* 根据文件路径读取文件内容
*
* @param fileInPath
* @throws IOException
*/
public static void getFileContent(Object fileInPath) throws IOException {
BufferedReader br = null;
if (fileInPath == null) {
return;
}
if (fileInPath instanceof String) {
br = new BufferedReader(new FileReader(new File((String) fileInPath)));
} else if (fileInPath instanceof InputStream) {
br = new BufferedReader(new InputStreamReader((InputStream) fileInPath));
}
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
方式一:
主要核心方法是使用getResource和getPath方法,这里的getResource("")里面是空字符串
public void function1(String fileName) throws IOException {
//注意getResource("")里面是空字符串
String path = this.getClass().getClassLoader().getResource("").getPath();
System.out.println(path);
String filePath = path + fileName;
System.out.println(filePath);
getFileContent(filePath);
}
方式二:
主要核心方法是使用getResource和getPath方法,直接通过getResource(fileName)方法获取文件路径,注意如果是路径中带有中文一定要使用URLDecoder.decode解码