maven工程打jar包,部署到服务器上以后,获取resource下文件的绝对路径是找不到该文件的
只能用流的方式获取,代码如下:
import lombok.extern.slf4j.Slf4j; import java.io.*; import java.util.ArrayList; import java.util.List; /** * Created by dell on 2019/05/26. */ @Slf4j public class FileTxtHandleUtil { public List<String[]> readTxt(String filePath) { log.info("txt文件路径:{}", filePath); try { List<String[]> result = new ArrayList<>(); InputStream stream = getClass().getClassLoader().getResourceAsStream(filePath); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); String lineTxt = null; while ((lineTxt = br.readLine()) != null) { String[] dataStr = lineTxt.split(" "); result.add(dataStr); } br.close(); } catch (FileNotFoundException e) { log.error("FileNotFoundException:" + e); } catch (IOException e) { log.error("IOException:" + e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { log.error("close br error:" + e); } } } return result; } catch (Exception e) { System.out.println("文件读取错误!"); } return null; } }
此工具在使用时只能实例化后调用方法,否则无效,调用方式如下