import java.awt.image.BufferedImageFilter; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * 用四種流實現文件的拷貝 * @author Administrator * */ public class CopyFileTest { public static void main(String[] args) { // TODO Auto-generated method stub String srcPath="d:/test.txt"; String destPath="f:/aaaa.txt"; copyFile(srcPath,destPath); //字節流實現文件的拷貝 copyFile2(srcPath,destPath);//字節緩沖流實現文件的拷貝 copyFile3(srcPath,destPath);//字符流實現文件的拷貝 copyFile4(srcPath,destPath);//字符緩沖流實現文件的拷貝 } /** * 用字節流實現文件的拷貝 * @param scrPath 源路徑名 * @param destPath 目標路徑名 */ private static void copyFile(String srcPath, String destPath) { // TODO Auto-generated method stub try (FileInputStream fis = new FileInputStream(srcPath); FileOutputStream fos = new FileOutputStream(destPath);){ //新建一個字節數組 byte[] b=new byte[1024]; //聲明一個整型常量,用來記錄數組的長度 int len; //文件的拷貝 while((len=fis.read(b))!=-1){ fos.write(b,0,len); } System.out.println("拷貝文件成功"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 字節緩沖流實現文件的拷貝 * @param scrPath 源路徑名 * @param destPath 目標路徑名 */ private static void copyFile2(String srcPath, String destPath) { // TODO Auto-generated method stub try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcPath)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath));){ //創建一個字節數組 byte[]b=new byte[1024]; //int常量用來接收位置 int len; //開始循環讀取字節,寫入文件 while((len=bis.read(b))!=-1){ bos.write(b,0,len); } System.out.println("文件拷貝成功"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 字符流實現文件的拷貝 * @param scrPath 源路徑名 * @param destPath 目標路徑名 */ private static void copyFile3(String srcPath, String destPath) { // TODO Auto-generated method stub try (FileReader fr = new FileReader(srcPath); FileWriter fw = new FileWriter(destPath);){ //創建一個字符數組 char[] ch=new char[1024]; //聲明一個變量 int len; while((len=fr.read(ch))!=-1){ fw.write(ch,0,len); } System.out.println("拷貝文件成功"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 字符緩沖流實現文件的拷貝 * @param srcPath 源路徑名 * @param destPath 目標路徑名 */ private static void copyFile4(String srcPath, String destPath) { // TODO Auto-generated method stub try (BufferedReader br = new BufferedReader(new FileReader(srcPath)); BufferedWriter bw = new BufferedWriter(new FileWriter(destPath));){ //字符緩沖是對文件一行讀取 String temp; //臨時變量記錄文件讀取的位置 while((temp=br.readLine())!=null){ bw.write(temp); bw.newLine();//讀取一行,並實現換行 } System.out.println("文件拷貝成功"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
個人總結:讀取數據,可以選用字符流,文件拷貝最好用字節流,字符流拷貝文件容易丟失數據,造成文件、圖像視頻打不開!