Java学习笔记29(IO字符流,转换流)
生活随笔
收集整理的這篇文章主要介紹了
Java学习笔记29(IO字符流,转换流)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
字符流:只能操作文本文件,與字節流的區別是,字節流是按照字節來讀取文件,而字符流是按照字符來讀取,因此字符流的局限性為文本文件
字符輸出流:Write類,使用時通過子類? ?每一次寫入都要刷新
package com.zs;import java.io.FileWriter; import java.io.IOException;public class Demo3 {public static void main(String[] args) throws IOException {FileWriter fw=new FileWriter("d:\\c.txt");fw.write(101);//輸入數字自動編碼fw.flush();//字符流每次操作都要使用flush方法刷新char[] ch={'a','b','c'};fw.write(ch);//輸入數組,寫字符數組 fw.flush();fw.write(ch,0,2);//寫部分字符數組選則的字符fw.write("hello java");//可以直接寫字符串 fw.close();} }字符輸入流:Reader類,通過子類
package com.zs.Demo2;import java.io.FileReader; import java.io.IOException;public class Demo2 {public static void main(String[] args) throws IOException {FileReader fr=new FileReader("d:\\c.txt");int len=0;while((len=fr.read())!=-1){//一個字符一個字符的讀System.out.println((char)len);}fr.close();FileReader fr1=new FileReader("d:\\c.txt");char[] c=new char[1024];//用字符數組讀數據,加快速度while((len=fr1.read(c))!=-1){System.out.println(new String(c,0,len));}fr.close();} }復制文件:與字節流相似,需要注意每次寫入后都要刷新
package com.zs.Demo2;import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;public class CopyFileByChar {public static void main(String[] args) {FileReader fr=null;FileWriter fw=null;try {fr=new FileReader("d:\\c.txt");fw=new FileWriter("e:\\c.txt");int len;char[] c=new char[1024];while((len=fr.read(c))!=-1){fw.write(c,0,len);fw.flush();}} catch (IOException e) {throw new RuntimeException("復制失敗");}finally {if (fw != null) {try {fw.close();} catch (IOException e) {throw new RuntimeException("釋放資源失敗");}finally {if (fr != null) {try {fr.close();} catch (IOException e) {throw new RuntimeException("釋放資源失敗");}}}}}} }
轉換流:字符流和字節流之間的橋梁
OutputStreamWriter類:字符轉字節
package com.zs.Demo2;import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter;public class CharToByte {public static void main(String[] args) throws IOException {FileOutputStream fo=new FileOutputStream("d:\\d.txt");//OutputStreamWriter(字節流對象,編碼格式);OutputStreamWriter fw=new OutputStreamWriter(fo,"utf-8");fw.write("你好");//這里本來d盤時字節流輸入的,可以使用字符流輸入字符串; fw.close();} }InputStreamReader:字節轉字符
package com.zs.Demo2;import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader;public class ByteToChar {public static void main(String[] args) throws IOException {FileInputStream fi=new FileInputStream("d:\\d.txt");InputStreamReader fr=new InputStreamReader(fi,"utf-8");char[] c=new char[1024];int len=0;while((len=fr.read(c))!=-1){System.out.println(new String(c,0,len));//你好 }} }注意讀取文本的編碼格式要一致
?
轉載于:https://www.cnblogs.com/Zs-book1/p/10595772.html
總結
以上是生活随笔為你收集整理的Java学习笔记29(IO字符流,转换流)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#常见编码方式总结
- 下一篇: Java中组合、继承与代理之间的关系。