Java中的字符型文件流FileReader和FileWriter詳細解讀
字符型文件流
與字節(jié)型文件流不同,字節(jié)型文件流讀取和寫入的都是一個又一個的字節(jié)。
而字符型文件流操作的單位是一個又一個的字符,字符型流認為一個字母是一個字符,而一個漢字也是一個字符。
字符型文件流一般只能夠用來操作一些文本格式的文件,即可以用記事本正常打開的文件。 (如:.txt .java .c .properties .html .js .xml)
字符型文件流解決了使用字節(jié)型文件流讀寫純文本文件時可能發(fā)生的中文亂碼問題,所以讀寫純文本文件是字符型文件流的強項。
它的用法與字節(jié)型文件流(FileInputStream,FileOutputStream)基本一致,只不過它每次讀寫的數組類型是char[]而不是byte[]。
我們說所有帶Reader字眼的都是字符型流。
而同時帶Stream和Reader字眼的它們是字節(jié)字符轉換流。
FileReader
繼承關系:
常用構造方法:
- FileReader(File file)
- FileReader(String fileName)
常用方法:
常用的4個
- read(char[] chars)
- read(char[] cbuf,int off,int len)
- skip(long n)
- close()
簡單嘗試: 準備一個.txt文件:
讀取它:
public static void main(String[] args) { File file = new File("F:\\test\\Test.txt"); FileReader fr = null; try { fr = new FileReader(file); char[] chars = new char[10];//每次讀取5個字符 int count = fr.read(chars); while (count!=-1){ String s = new String(chars, 0, count); System.out.println(s); count = fr.read(chars); } } catch (IOException e) { e.printStackTrace(); }finally { if (fr!=null){ try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } }
執(zhí)行結果:
換行是我打印的時候加上去的(每讀取10個字符打印一次)。
FileWriter
繼承關系:
常用構造方法:
- FileWriter(File file)
- FileWriter(File file, boolean append)
- FileWriter(String fileName)
- FileWriter(String fileName, boolean append)
常用方法:
常用的6個
- write(char[] cbuf)
- write(String str)
- write(String str,int off,int len)
- write(String cbuf,int off,int len)
- close()
- flush()
簡單嘗試:
public static void main(String[] args) { File file = new File("F:\\test\\log.txt"); //log.txt可以不存在,test文件夾必須存在 FileWriter fw = null; try { fw = new FileWriter(file,true);//要追加寫入數據 String str = "文字是人類用表義符號記錄表達信息,使之傳之久遠的方式和工具?,F代文字大多是記錄語言的工具。人類往往先有口頭的語言后產生書面文字,很多方言和小語種,有語言但沒有文字。文字的不同體現了國家和民族的書面表達的方式和思維不同。文字使人類進入有歷史記錄的文明社會。\n" + "Text is a way and tool for human beings to record and express information by means of symbolic meaning.Modern writing is mostly a tool for recording language.Humans tend to have spoken languages before they have written languages, many dialects and smaller languages that have languages but no words.The different characters reflect the different ways and thinking of the written expression of the country and nation.Writing enabled mankind to enter a civilization with a historical record."; char[] chars = str.toCharArray(); fw.write(chars); } catch (IOException e) { e.printStackTrace(); }finally { if (fw!=null){ try { fw.close(); } catch (IOException e) { e.printStackTrace(); } } } }
執(zhí)行結果:
到此這篇關于Java中的字符型文件流FileReader和FileWriter詳細解讀的文章就介紹到這了,更多相關Java的字符型文件流內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
MyBatis-plus更新對象時將字段值更新為null的實現方式
mybatis-plus在執(zhí)行更新操作,當更新字段為 空字符串 或者 null 的則不會執(zhí)行更新,如果要將指定字段更新null,可以通過以下三種方式實現,感興趣的小伙伴跟著小編一起來看看吧2023-10-10在lambda的foreach遍歷中break退出操作(lambda foreach break)
這篇文章主要介紹了在lambda的foreach遍歷中break退出操作(lambda foreach break),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09