Java IO 复制一个文件到另一个文件夹下

这是原来学io的时候,老师举得一个比较有代表性的题:
复制一个文件到另一个文件夹。
我们来看源码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
    public static void main(String[] args) {
        File inFile = new File("E:\\a.txt");
        String outPath = "D:\\";
        new Test().copy(inFile, outPath);
    }

    public void copy(File inFile , String outPath){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(inFile);
            fos = new FileOutputStream(new File(outPath,inFile.getName()));
            byte[] bytes = new byte[1024];
            int len = 0;
            while((len=fis.read(bytes)) != -1){
                fos.write(bytes, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if (fos==null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis==null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

这里面很明显的需要操作File类,并且使用input和output来执行对文件的读写;

然后当文件写入进来时,创建一个btye数组来接收文件的字节数据,再在下面的循环判断中判断len不等于-1,那就用write读出去。

最后别忘了在finally块中关闭流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值