版權聲明:本文為xing_star原創文章,轉載請注明出處!
本文同步自http://javaexception.com/archives/128
java讀取文本文件內容
今天寫代碼寫着要調試一個很長的字符串,就用idea新建了text文本,存放長字符串的內容。結果發現讀取文本文件內容的java代碼不怎么會寫了,果然是面向百度編程,面向control c 或者control v編程,尷尬。
最終的代碼如下:
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(); }
到此就結束了,留個小問題,這種方式只能讀取普通的文本文件,對於二進制之類的文件,是不可以的,那應該如何做呢,嗯,等碰到這樣場景的需求再記錄下來吧。