您好,登錄后才能下訂單哦!
這篇文章主要講解了“Java怎么實現讀取項目中的文件”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Java怎么實現讀取項目中的文件”吧!
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.76</version> </dependency>
重點部分
. /代表同級目錄
…/ 代表上級目錄(兩個點)
/ 代表根目錄
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; } }
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; }
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); } }
<!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> <h2>Click Style</h2> </body> </html>
感謝各位的閱讀,以上就是“Java怎么實現讀取項目中的文件”的內容了,經過本文的學習后,相信大家對Java怎么實現讀取項目中的文件這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。