java Properties读取配置文件
-
在编辑器测试:
/** * 取得当前类路径下的 resName资源的完整路径 * url.getPath()获取到的路径被utf-8编码了 * 需要用URLDecoder.decode(path, "UTF-8")解码 * * @param resName 需要获取完整路径的资源,需要以/打头 * @return 完整路径 */ public static String getResourcePath(String resName) { URL url = ConfigProperties.class.getResource(resName); String path = url.getPath(); String decodePath = null; try { decodePath = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return decodePath; }
-
打包运行
protected void loadFromFile() { InputStream in = null; InputStreamReader ireader = null; try { in = ConfigProperties.class.getResourceAsStream(propertiesName); //解决读非UTF-8编码的配置文件时,出现的中文乱码问题 ireader = new InputStreamReader(in, "utf-8"); properties.load(ireader); } catch (IOException e) { e.printStackTrace(); } finally { closeQuietly(ireader); } } public static void closeQuietly(java.io.Closeable o) { if (null == o) return; try { o.close(); } catch (IOException e) { e.printStackTrace(); } }