java讀取相對目錄的文件,讀取jar包相對目錄的文件:
package com.wjj.application.util;
import java.io.*;
/**
* 文件工具集
* @author hank
* @since 2020/3/9 0009 下午 17:58
*/
public class FileUtils {
/**
* 讀取相對路徑下的的文本文件
* @param filePath
* @return 存在返回內容,不存在返回null
* @throws IOException
*/
public static String readRelativeFile(String filePath) throws IOException {
// 只允許讀取相對目錄文件
String relativeFilePath = "."+ File.separator+filePath;
File file = new File(relativeFilePath);
// 不存在或者不是文件返回null
if(!file.exists() || !file.isFile()){
return null;
}
try(InputStreamReader reader = new InputStreamReader(new FileInputStream(file))) {
try (BufferedReader br = new BufferedReader(reader)) {
StringBuilder content = new StringBuilder();
String data = null;
while ((data = br.readLine()) != null) {
content.append(data);
}
return content.toString();
}
}
}
}