java-io FileInputStream文件拷贝

发布时间 2023-04-10 17:45:53作者: 逆梦

1、编写代码

main方法:

public static void main(String[] args) throws IOException {
        String pathFileUrl ="C:/Users/xxx/Desktop/boardDevice/videoFiles/1677749222547.docx";
        //String pathFileUrl ="D:\\images\\6d3a8ae483ba9016284d582b3af98670.png";
        //String pathFileUrl ="D:\\boardDevice\\video\\1677829260585.mp4";
        copyFileLogic(pathFileUrl);
    }
copyFileLogic处理路径信息:
public static void copyFileLogic(String oldPath) throws IOException {
        String newPath = "C:/Users/xxx/Desktop/boardDevice/copyFiles";
        File file = new File(newPath);
        if (!file.exists()){
            file.mkdirs();
        }
        String[] split = oldPath.split("/");
        String fileName = split[split.length - 1];
        String suffix = fileName.split("\\.")[1];
        String files = newPath +"/"+System.currentTimeMillis()+"."+suffix;
        copyFileMethod(oldPath,files);
    }
copyFileMethod文件拷贝:
public static void copyFileMethod(String oldPath,String newPath) throws IOException {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fis = new FileInputStream(new File(oldPath));
            fos = new FileOutputStream(newPath);
            bos=new BufferedOutputStream(fos);
            byte[] bytes=new byte[1024];
            int len = 0;
            while ((len = fis.read(bytes))!= -1){
                bos.write(bytes,0,len);
            }
        }finally {
            if (fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }