Java實現讀取項目中文件(.json或.properties)的方法詳解
1. 讀取json file
1.1 Json dependency
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.76</version> </dependency>
1.2 字節流
重點部分
- . /代表同級目錄
- …/ 代表上級目錄(兩個點)
- / 代表根目錄
public class FileService { public JSONObject reader(){ JSONObject resultJson = null; String file = "src/main/resources/config_dev.json"; InputStream is = null; try { is = new FileInputStream(file);//操作 byte[] bytes = new byte[5000];//數組容量超級大,一次能將中英混合文本全部讀取完 int len = -1; while ((len = is.read(bytes)) != -1) { String str = new String(bytes, 0, len, "UTF-8"); resultJson = process(str); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally {//釋放資源 try { if (null != is) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } return resultJson; } private static JSONObject process(String content) { JSONObject json = JSONObject.parseObject(content); return json; } }
1.3 buffer reader
public static String reader(String filePath) { try { File file = new File(filePath); if (file.isFile() && file.exists()) { InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8"); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = bufferedReader.readLine(); while (lineTxt != null) { return lineTxt; } } } catch (UnsupportedEncodingException | FileNotFoundException e) { System.out.println("Cannot find the file specified!"); e.printStackTrace(); } catch (IOException e) { System.out.println("Error reading file content!"); e.printStackTrace(); } return null; }
2. 讀取properties file
public void readPropertiesFile() { Properties pro = new Properties(); InputStream is = this.getClass().getResourceAsStream("/application.properties"); try { pro.load(is); Enumeration en = pro.propertyNames(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); String value = pro.getProperty(key); System.out.println(key + "--" + value); } } catch (IOException e) { throw new RuntimeException(e); } }
3. 好看的css樣式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <link rel="stylesheet" href="https://qxhut.cn/zb_users/plugin/Jz52_click/click.css"> <script src="https://qxhut.cn/zb_users/plugin/Jz52_click/click.js"></script> <h1>Click Style</h1> </body> </html>
到此這篇關於Java實現讀取項目中文件(.json或.properties)的方法詳解的文章就介紹到這瞭,更多相關Java讀取項目文件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!