2019-09-03 14:42:12 4570瀏覽
今天千鋒扣丁學(xué)堂Java在線培訓(xùn)老師給大家分享一篇關(guān)于JAVA讀取文本文件內(nèi)容實例代碼的詳細(xì)介紹,希望對同學(xué)們有所幫助,下面我們來看一下其中主要部分源碼!
public static String readFileContent(String fileName) { File file = new File(fileName); BufferedReader reader = null; StringBuffer sbf = new StringBuffer(); try { reader = new BufferedReader(new FileReader(file)); String tempStr; while ((tempStr = reader.readLine()) != null) { sbf.append(tempStr); } reader.close(); return sbf.toString(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { e1.printStackTrace(); } } } return sbf.toString(); }
public String readToString(String fileName) { String encoding = "UTF-8"; File file = new File(fileName); Long filelength = file.length(); byte[] filecontent = new byte[filelength.intValue()]; try { FileInputStream in = new FileInputStream(file); in.read(filecontent); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { return new String(filecontent, encoding); } catch (UnsupportedEncodingException e) { System.err.println("The OS does not support " + encoding); e.printStackTrace(); return null; } }
【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】 【掃碼進入JavaEE/微服務(wù)VIP免費公開課】
查看更多關(guān)于“Java開發(fā)資訊”的相關(guān)文章>>