Java 图片复制

图片复制

public static void main(String[] args) {
        File file = new File("F:\\up2.jpg");//要复制的图片地址
        File file2=new File("F:\\Hello\\up2.jpg");//复制后的图片地址
        InputStream fis= null;//创建输入字节流
        DataInputStream dis=null;//创建数据输入流
        OutputStream fos=null;//创建输出字节流
        DataOutputStream dos=null;//创建输出数据流
        try {
            //将要复制的图片地址给输入字节流来读取
            fis = new FileInputStream(file);
            //再把输入字节流给数据输入流
            dis=new DataInputStream(fis);

            //将复制后的图片地址给输出字节流
            fos=new FileOutputStream(file2);
            //再把输出字节流给数据输出流
            dos=new DataOutputStream(fos);
            //定义一个变量来控制是否读取
            int index=0;
            //index=dis.read()  dis.read()读出来的是ascii码 如果读完那么结果就是-1
            while ((index=dis.read())!=-1){
                //每读出来就写出去
                dos.write(index);
            }
            //将缓冲区里面的东西给刷出去
            dos.flush();
            System.out.println("over");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //不管读的成不成功必须关流  从下往上关
                dos.close();
                fos.close();
                dis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Java的IO类库来复制并改名图片。以下是一个简单的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class ImageCopyAndRename { public static void main(String[] args) { String sourcePath = "path/to/source/image.jpg"; // 原始图片路径 String targetPath = "path/to/target/image.jpg"; // 目标图片路径 try (FileInputStream fis = new FileInputStream(new File(sourcePath)); FileOutputStream fos = new FileOutputStream(new File(targetPath))) { byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } } catch (IOException e) { e.printStackTrace(); } File targetFile = new File(targetPath); String newFileName = "new_image_name.jpg"; File renamedFile = new File(targetFile.getParentFile(), newFileName); if (targetFile.renameTo(renamedFile)) { System.out.println("图片复制并改名成功!"); } else { System.out.println("图片复制并改名失败!"); } } } ``` 在这个示例代码中,我们首先使用FileInputStream和FileOutputStream来复制原始图片。然后,我们使用File类的renameTo()方法来改名目标文件。注意,我们首先创建一个新的File对象,它是目标文件的父文件夹和新文件名的组合,然后使用renameTo()方法将目标文件重命名为新的文件名。 当运行这段代码时,请确保将sourcePath和targetPath替换为您自己的路径,以及将newFileName替换为您想要的新文件名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值