java(IO)copy,字节字符

package com.day21.IO;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//字符
public class FileCopy {
    //编写程序FileCopy.java,在测试方法中,将FileCopy.java复制为FileCopy.java.bak文件;
    // 查看FileCopy.java.bak文件的内容,验证复制是否正确。
    public static void main(String[] args) {
        FileReader fileReader = null;
        FileWriter fileWriter = null;
        try {
            fileReader = new FileReader("D:\\javaSE\\基础语法\\src\\com\\day21\\IO\\FileCopy.java");
            fileWriter = new FileWriter("FileCopy.java.bak");
            char[] buf = new char[100];
            //以读为主导
            int realCount = fileReader.read(buf);
            while (realCount != -1) {
                //1)处理已经读的数据
                //在处理已经读到的数据时,写文件

                fileWriter.write(buf,0,realCount);

                //2)继续读
                realCount = fileReader.read(buf);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
package com.day21.IO;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//字节
public class FileCopy2 {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream("D:\\KwDownload\\song\\沉默是金.mp3");
            fileOutputStream = new FileOutputStream("沉默不是金.mp3");
            byte[] buf = new byte[8192];
            int read = fileInputStream.read(buf);
            while (read != -1){
                fileOutputStream.write(buf,0,read);
                read = fileInputStream.read(buf);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream !=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值