Java關於使用IO流copy檔案的方法
阿新 • • 發佈:2018-12-09
關於使用IO流中的方法將A檔案內容複製到B檔案中
首先建立一個檔案
// 建立新的檔案 File file = new File("D:\\111Java高階\\demo\\asd1.txt"); boolean createNewFile = file.createNewFile(); System.out.println(createNewFile); // 向檔案裡新增內容 FileWriter fw = new FileWriter("D:\\111Java高階\\demo\\asd1.txt"); fw.write("冥冥之中,該來則來,無處可逃"); fw.flush();
第一種方式:
使用位元組流(InputStream)來操作檔案的copy
// InputStream是抽象類所以用其子類FileInputStream來建立物件,當然也可以直接用子類來建立物件 InputStream in = new FileInputStream("D:\\111Java高階\\demo\\asd1.txt"); OutputStream out = new FileOutputStream("D:\\111Java高階\\demo\\asd2.txt"); // 定義一個len變數用來接收讀取的位元組 int len = 0; // 建立一個位元組陣列,用來存取該位元組流讀取的位元組數 byte[] buff = new byte[1024]; // 將位元組陣列引數傳入read()方法中 while ((len = in.read(buff)) != -1) { // write()方法傳入的三個引數,引數一:位元組陣列 引數二:開始讀取的位置 引數三:讀取的長度 out.write(buff, 0, len); out.flush(); // System.out.print(new String(buff, 0, len)); }
一個漢字為兩個位元組, 數字、英文字元為一個位元組
第二種方式:
使用緩衝位元組流(BufferedInputStream)來操作檔案的copy
// 傳的引數為物件(將緩衝指定檔案的輸入) BufferedInputStream in = new BufferedInputStream(new FileInputStream( "D:\\111Java高階\\demo\\asd1.txt")); BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream("D:\\111Java高階\\demo\\asd2.txt")); // 定義一個len變數用來接收讀取的位元組 int len = 0; // 建立一個位元組陣列,用來存取該位元組流讀取的位元組數 byte[] buff = new byte[1024]; // 將位元組陣列引數傳入read()方法中 while ((len = in.read(buff)) != -1) { // write()方法傳入的三個引數,引數一:位元組陣列 引數二:開始讀取的位置 引數三:讀取的長度 out.write(buff, 0, len); out.flush(); // System.out.print(new String(buff, 0, len)); }
第三種方式:
使用字元流(Reader)來操作檔案的copy
// Reader是抽象類所以用其子類FileReader來建立例項物件
Reader fre = new FileReader("D:\\111Java高階\\demo\\asd1.txt");
Writer fwr = new FileWriter("D:\\111Java高階\\demo\\asd2.txt");
// 定義一個int變數 接收讀取的文字每一行的資料
int ch = 0;
// fre,read()讀出來的為碼值
while ((ch = fre.read()) != -1) {
// 將對應的碼值轉換為char字元
fwr.write(String.valueOf((char) ch));
fwr.flush();
}
第四種方式:
使用緩衝字元流(BufferedReade)來操作檔案的copy
// 傳的引數為物件(將緩衝指定檔案的輸入)
BufferedReader bin = new BufferedReader(new FileReader(
"D:\\111Java高階\\demo\\asd1.txt"));
BufferedWriter bout = new BufferedWriter(new FileWriter(
"D:\\111Java高階\\demo\\asd2.txt"));
// 定義一個字串變數 接收讀取的文字每一行的資料
String str = "";
// 遍歷輸入寫出資料
while ((str = bin.readLine()) != null) {
bout.write(str);
bout.flush();
}
可以看出位元組流和緩衝位元組流寫出方式一樣,字元流和緩衝字元流的寫出方式一樣,而緩衝位元組流和緩衝字元流的建立物件方式類似 readLine()方法是BufferedReader緩衝字元流特有的方法,讀取一行資料,為字串型別
一般使用字元緩衝字元流讀(BufferedReader)寫(BufferedWriter)要方便一些,他可以直接以字串創的形式讀寫(ReadLine())當然這個是視情況而定的