天天看點

使用I/O流 複制檔案(位元組流,字元流)

//檔案複制    字元流
        FileReader fr=null;
        BufferedReader br=null;
        FileWriter fw=null;
        BufferedWriter bw=null;
        try {
            //讀取文本
            fr=new FileReader("H:\\i_o\\檔案複制\\test1.txt");
            br=new BufferedReader(fr);
            fw=new FileWriter("H:\\i_o\\檔案複制\\newtest1.txt");
            bw=new BufferedWriter(fw);
            //循環讀取檔案内容寫入新的檔案中
            String c;
            while((c=br.readLine())!=null){
                bw.write(c);
            }
            System.out.println("檔案複制已完成,請檢視!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                bw.close();
                fw.close();
                br.close();
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }





//檔案複制   位元組流
        FileInputStream fis=null;
        FileOutputStream fos=null;
        //讀取檔案
        try {
            fis=new FileInputStream("H:\\i_o\\檔案複制\\test1.txt");
            //寫入到新檔案中
            fos=new FileOutputStream("H:\\i_o\\檔案複制\\newtest.txt");
            //循環讀取檔案 寫入到新檔案中   方法1
            int n=-;
            while((n=fis.read())!=-){
                fos.write(n);
            }
            //循環讀取檔案到數組中, 寫入到新檔案中  方法2
//          byte[] b=new byte[1024];
//          int n=-1;
//          while((n=fis.read(b))!=-1){
//              fos.write(b,0,n);
//          }
            System.out.println("檔案複制已完成,請檢視!");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                fis.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }