標籤:字元流 filereader
標題
import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.Reader;import java.io.Writer;/* * FileReader/FileWriter類 * 檔案字元輸入輸出資料流 */public class Test03 { public static void main(String[] args) throws IOException { test3(); } // 檔案字元輸入資料流 public static void test1() throws IOException { Reader reader = new FileReader("D:\\Java\\hello.txt"); // 每次讀取一個字元 int data = reader.read();// 返回一個int類型的字元值 while (data != -1) { System.out.println((char) data); data = reader.read(); } reader.close(); } // 檔案字元輸出資料流 public static void test2() throws IOException { Writer writer = new FileWriter("D:\\Java\\hello.txt", true); writer.write("餘書磊"); writer.flush(); System.out.println("使用字元輸出資料流寫入成功!"); writer.close(); } // 檔案複製 public static void test3() throws IOException { Reader reader = new FileReader("D:\\Java\\hello.txt"); Writer writer = new FileWriter("D:\\Java\\hello_bak.txt"); //方式一:每次複製一個字元 int data = reader.read(); while (data != -1) { writer.write(data); data = reader.read(); } //方式二:每次複製一個字元數組 char[] buffer=new char[10]; int num=reader.read(buffer);//返回實際讀取的長度 while(num!=-1){ writer.write(buffer, 0, num); num=reader.read(buffer); } //方式三:將讀取的字元拼接到字串中,再寫入 StringBuffer sb=new StringBuffer(); int data = reader.read(); while (data != -1) { sb.append((char)data); data = reader.read(); } writer.write(sb.toString()); writer.flush(); System.out.println("檔案複製成功!"); writer.close(); reader.close(); } /* * 字元流無法複製二進位檔案,位元組流可以 */ public static void test4() throws IOException { BufferedInputStream bis=new BufferedInputStream(new FileInputStream("D:\\Java\\ascii.jpg")); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\Java\\ascii_bak.jpg")); int data = bis.read(); while (data != -1) { bos.write(data); data = bis.read(); } bos.flush(); System.out.println("檔案複製成功!"); bos.close(); bis.close(); }}
JAVA學習筆記(三十二)- 字元流 FileReader & FileWriter