IO流复制图片

2021/11/14 23:13:52

本文主要是介绍IO流复制图片,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

package IODemo;

/**
 * @author Alina
 * @date 2021年11月14日 4:32 下午
 * 复制文件到指定目录
 *
 */
import java.io.*;
public class IOcopyfile {
    public static void main(String[] args) {
        CopyDir(new File(“源文件”),new File(“目标文件”));
    }
    public static void CopyDir(File source,File target){
        //获取数据源下所有目录名字
        String SourceDirName = source.getName();
        //System.out.print(SourceDirName);
        //在新目录下创建同样的文档,只有File 类有创建文件的功能
        File TargetNewDir = new File(target,SourceDirName);
        // System.out.print(TargetNewDir);
        //创建新目录
        TargetNewDir.mkdir();

        //2.遍历数据源下所有文件
        File[] files = source.listFiles();
        //使用for循环遍历目录下所有文件
        for(File sourceFile: files){
           // System.out.print(sourceFile);
           // 定义字符串,存储文件的名字
            String sourceFileName = sourceFile.getName();
            //在新目录下创建相同的文件名
            File newTargetFileName = new File(TargetNewDir,sourceFileName);
            //复制文件
            copyFunction(sourceFile,newTargetFileName);

        }

    }
    public static void copyFunction(File source,File target){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try{
            fis = new FileInputStream(source);
            fos = new FileOutputStream(target);
            byte[]  bytes = new byte[1024];
            int s = 0;
            while ((s = fis.read(bytes))!=-1){
                fos.write(bytes,0,s);
            }
        }catch (Exception e){
            throw new RuntimeException("复制失败");
        }finally {
            try{
                if (fos != null){
                    fos.close();
                }
            }catch (Exception e){
                throw new RuntimeException("运行失败");
            }finally {
                try {
                    if (fis!=null) {
                        fis.close();
                    }
                }catch (Exception e){
                    throw new RuntimeException("运行失败");
                }
            }

        }
    }
}



这篇关于IO流复制图片的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程