標籤:java 字元流
/* 字元流 Reader Writer--FileWriter 字元流緩衝區:提高流操作效率 BufferedReader BufferedWriter */package pack;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.FileWriter;import java.io.LineNumberReader;public class Main { public static void sys(Object obj) { System.out.println(obj); } public static void main(String[] args) throws Exception{ //method1();//FileWriter //method2();//FileWriter //method3();//FileReader //method4();//拷貝檔案 //method5();//BufferedWriter //method6();//FileReader //method7();//拷貝檔案 method8();//LineNumberReader加序號功能 } public static void method1() throws Exception { FileWriter fw = new FileWriter("E:\\1.txt"); fw.write("abc"); //將字串寫入流中 fw.flush(); //重新整理流對象中的緩衝中的資料 fw.close(); //關資源 } public static void method2() throws Exception { FileWriter fw = new FileWriter("E:\\1.txt",true);//不覆蓋存在的檔案 fw.write("cc\r\nc"); //換行 fw.flush(); fw.close(); } public static void method3() throws Exception { FileReader fr = new FileReader("E:\\1.txt"); /*int ch = 0; while((ch=fr.read())!=-1) { sys((char)ch); }*/ /*char[] buf = new char[9]; int ch = fr.read(buf);//寫入數組中,ch為讀到的個數 sys(new String(buf));//輸出數組*/ char[] buf = new char[3]; int num = 0; while((num=fr.read(buf))!=-1) //個數不是-1 sys(new String(buf,0,num));//從0到num fr.close(); } /*拷貝檔案*/ public static void method4() throws Exception { /*FileReader fr = new FileReader("E:\\1.txt"); FileWriter fw = new FileWriter("E:\\2.txt"); int ch = 0; while((ch=fr.read())!=-1) fw.write(ch); fr.close(); fw.close();*/ FileReader fr = new FileReader("E:\\1.txt"); FileWriter fw = new FileWriter("E:\\2.txt"); char[] buf = new char[1024]; int len = 0; while((len=fr.read(buf))!=-1) fw.write(buf,0,len); fw.close(); fr.close(); } public static void method5() throws Exception { /*緩衝區是為了提高效率,得先有流*/ FileWriter fw = new FileWriter("E:\\1.txt"); BufferedWriter bufw = new BufferedWriter(fw); bufw.write("kk"); bufw.newLine(); //寫入分行符號 bufw.write("gg"); bufw.flush(); bufw.close();//關閉緩衝區就是關閉緩衝區作用的流對象 } public static void method6() throws Exception { FileReader fr = new FileReader("E:\\1.txt"); BufferedReader bufr = new BufferedReader(fr); String line = null; while((line=bufr.readLine())!=null)//返回空表示讀到末尾 sys(line); bufr.close(); } /*拷貝檔案*/ public static void method7() throws Exception { BufferedReader bufr = new BufferedReader(new FileReader("E:\\1.txt")); BufferedWriter bufw = new BufferedWriter(new FileWriter("E:\\2.txt")); String line = null; while((line=bufr.readLine())!=null) bufw.write(line); bufr.close(); bufw.close(); } public static void method8() throws Exception { FileReader fr = new FileReader("E:\\1.txt"); LineNumberReader lnr = new LineNumberReader(fr); String line = null; while((line=lnr.readLine())!=null) sys(lnr.getLineNumber()+":"+line); lnr.close(); }}
java字元流