开发过程中,必不可少的需要读取文件,对于打包方式的不同,还会存在一些坑,比如以jar包方式部署时,文件都存在于jar包中,某些读取方式在开发工程中都可行,但是打包后,由于文件被保存在jar中,会导致读取失败。 这时就需要通过类加载器读取文件,类加载器可以读取jar包中的class类当然也可以读取jar包中的文件。
// 方法1:获取文件或流 this.getClass().getResource("/")+fileName; this.getClass().getResourceAsStream(failName); // 方法2:获取文件 File file = org.springframework.util.ResourceUtils.getFile("classpath:test.txt"); // 方法3:获取文件或流 ClassPathResource classPathResource = new ClassPathResource("test.txt"); classPathResource .getFile(); classPathResource .getInputStream(); // >>>>>>>>>>>>>>>> 下面方法可以读取jar包下文件 // 方法1 InputStream io = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.txt"); // 方法2 InputStream io = ClassLoader.getSystemResourceAsStream("test.txt");
附带自己写的工具类:
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ResourceUtils; /** * 配置文件工具类<br> * 使用到的配置变量统一定义在此类 * * @author lisheng4 * */ public class PropertiesUtils { private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class); private static final String SERVER_CONSTANTS = "classpath:server-constants.properties"; private static volatile Map<String,Object> paramsMap = null; private static Date reloadDate = null; private static final int EXPIRED_TIME = 10 * 60 * 1000; private static final String EQUAL_SIGN = "="; private static final String NUMBER_SIGN = "#"; public static final String WECHAT_URL = "wechat.url"; public static final String WECHAT_TOKEN_URL = "wechat.tokenUrl"; /** 试点地区取件码短信新模板(先微后短引导关注微信)项目的城市白名单 */ public static final String CITY_WHILTE_LEAD_WECHAT_WITH_SMS = "cityWhilteLeadWeChatWithSMS"; public static String getResources(String key) { if(StringUtils.isEmpty(key)) { return ""; } if(paramsMap == null || isExpired()) { return getResourcesReload(key); } return (String) paramsMap.get(key); } private static boolean isExpired() { if(reloadDate == null) { return true; } if((new Date().getTime()- reloadDate.getTime()) < EXPIRED_TIME) { return false; } return true; } private static String getResourcesReload(String key) { getAllResources(); if(paramsMap == null || isExpired()) { return ""; } return (String) paramsMap.get(key); } private static void getAllResources() { BufferedReader br = null; try { if(paramsMap == null || isExpired()) { synchronized (PropertiesUtils.class) { if(paramsMap == null || isExpired()) { long t1 = System.currentTimeMillis(); paramsMap = new HashMap<String,Object>(); File file = ResourceUtils.getFile(SERVER_CONSTANTS); br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line = null; while((line = br.readLine()) != null) { if(StringUtils.isEmpty(line) || StringUtils.isEmpty(line.trim()) || line.indexOf(NUMBER_SIGN) == 0) { continue; } String[] strAry = line.split(EQUAL_SIGN); if(strAry != null && strAry.length == 2 && StringUtils.isNotEmpty(strAry[0].trim())) { paramsMap.put(strAry[0].trim(), strAry[1].trim()); } } reloadDate = new Date(); long t2 = System.currentTimeMillis(); logger.info("加载配置文件:{}, 耗时:{} 毫秒", SERVER_CONSTANTS, t2-t1); } } } } catch (Exception e) { logger.error("获取配置文件参数异常:resourceLocation={}",SERVER_CONSTANTS); }finally { if(br != null) { try { br.close(); } catch (IOException e) { //e.printStackTrace(); } } } } } // static { // //getAllResources(); // System.out.println("读取到的值wechat.url=" + getResources(WECHAT_URL)); // System.out.println("读取到的值wechat.tokenUrl=" + getResources(WECHAT_TOKEN_URL)); // System.out.println("读取到的值paramsMap=" + JSON.toJSONString(paramsMap)); // } // public static void main(String[] args) { // String line = "aaa=111"; // //String line = " aaa = 111 "; // //String line = " aaa = "; // //String line = " = "; // //String line = "#aaa=111"; // paramsMap = new HashMap<String,Object>(); // if(line.indexOf("#") == 0) { // System.out.println("注释:" + line); // }else { // String[] strAry = line.split("="); // if(strAry != null && strAry.length == 2 && StringUtils.isNotEmpty(strAry[0].trim())) { // paramsMap.put(strAry[0].trim(), strAry[1].trim()); // } // } // System.out.println("paramsMap:" + paramsMap); // System.out.println("aaa:" + paramsMap.get("aaa")); // } }