Java IO 拷贝MP3文件,包括递归子文件夹下的文件

最近从网上找了一套杰伦歌曲全集,文件夹和子文件夹太多,想着写个简单的IO程序拷贝一下。代码如下


package com.tool;

import java.io.*;

public class CopyJayMP3FileTool {
    public static void main(String[] args) {
        String inputPath = "E:\\";
        String outputPath = "D:\\JayChou\\";
        File file = new File(inputPath);
        copyFile(file, outputPath);

}
    public static void copyFile(File file, String outputPath){
        if (file.isDirectory()) {
            File[] fileList = file.listFiles();
            if (fileList != null && fileList.length > 0){
                for (File file1: fileList) {
                    copyFile(file1, outputPath);
                }
            }
        } else if (file.isFile() && file.getName().endsWith(".mp3")) {
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            File outputFile = new File(outputPath + file.getName());
            boolean exists = outputFile.exists();
            try {
                bis = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()));
                bos = new BufferedOutputStream(new FileOutputStream(outputPath + file.getName()));
                int len = 0;
                byte[] bytes = new byte[2048];
                while ((len = bis.read(bytes)) != -1) {
                    bos.write(bytes, 0, len);
                }
                bos.flush();
                if (exists){
                    System.out.println(file.getName() + " is already exists will overwritten to " + outputPath);
                }else {
                System.out.println(file.getName() + " is already copied to " + outputPath);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (bis != null){
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bos != null){
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

posted @ 2020-04-16 10:15  火火火火四火  阅读(188)  评论(0编辑  收藏  举报