Java IO流 系统找不到指定的文件

这篇博客展示了如何使用Java进行文件复制操作,包括通过字节流和字节数组两种方式。博主在实现过程中遇到了FileNotFoundException,原因是输入流与输出流的路径写反了。通过调整后,问题得到解决,代码能够正确地从源路径复制文件到目标路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

话不多说 直接上代码

//main方法
public static void main(String[] args) throws IOException {
        String srcpath = "day11_data/img/cropped-1920-1080-1012576.jpg";
        String dppath = "day11_data/d/bbb.jpg";

       copyFile(srcpath, dppath);
        //copyFileByArray(srcpath,dppath);
    }
//copyFile方法
public static void copyFile(String srcPath, String dpPath) throws IOException {
        //准备流
        FileOutputStream fos = new FileOutputStream(srcPath);
        FileInputStream fis = new FileInputStream(dpPath);

        int b;
        while ((b = fis.read()) != -1) {
            fos.write(b);
            //System.out.println(b);
        }

        fos.close();
        fis.close();
    }

    public static void copyFileByArray(String srcPath, String destPath) throws IOException {
        //准备流
        FileInputStream fis = new FileInputStream(srcPath);
        FileOutputStream fos = new FileOutputStream(destPath);

        long l = System.currentTimeMillis();
        //输入
        int len;
        byte[] bytes = new byte[1024];
        while ((len = fis.read(bytes)) != -1) {
            //输出
            fos.write(bytes, 0, len);
        }

        //关闭流
        fos.close();
        fis.close();
        long l2 = System.currentTimeMillis();
        System.out.println("复制图片用了" + (l2 - l) + "毫秒");
    }
//报错
Exception in thread "main" java.io.FileNotFoundException: day11_data\d\bbb.jpg (系统找不到指定的文件。)

原因是输入流与输出流的路径写反了

		FileOutputStream fos = new FileOutputStream(srcPath);
        FileInputStream fis = new FileInputStream(dpPath);

这里,输入流应该是srcPath,输出流是dpPath,调换一下就可以解决这个问题了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值