简体   繁体   English

如何从目录和子目录复制具有某些扩展名的所有文件?

[英]How to copy all files with certain extensions from a directory and sub directories?

I know how to copy a file from one directory to another, what I would like help on is copy a file with .jpg or .doc extension. 我知道如何将文件从一个目录复制到另一个目录,我想帮助的是复制扩展名为.jpg或.doc的文件。

So for example. 例如。

Copy all files from D:/Pictures/Holidays 复制D:/Pictures/Holidays所有文件

Scanning all folders in the above path and transfer all jpg's to a destination provided. 扫描上述路径中的所有文件夹,并将所有jpg传输到提供的目的地。

This works, but the file 'copy(File file, File outputFolder)' method could be enhanced for large files: 这可行,但是可以针对大文件增强文件'copy(File file,File outputFolder)'方法:

package net.bpfurtado.copyfiles;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFilesFromType
{
    public static void main(String[] args)
    {
        new CopyFilesFromType().copy("jpg", "C:\\Users\\BrunoFurtado\\Pictures", "c:/temp/photos");
    }

    private FileTypeOrFolderFilter filter = null;

    private void copy(final String fileType, String fromPath, String outputPath)
    {
        filter = new FileTypeOrFolderFilter(fileType);
        File currentFolder = new File(fromPath);
        File outputFolder = new File(outputPath);
        scanFolder(fileType, currentFolder, outputFolder);
    }

    private void scanFolder(final String fileType, File currentFolder, File outputFolder)
    {
        System.out.println("Scanning folder [" + currentFolder + "]...");
        File[] files = currentFolder.listFiles(filter);
        for (File file : files) {
            if (file.isDirectory()) {
                scanFolder(fileType, file, outputFolder);
            } else {
                copy(file, outputFolder);
            }
        }
    }

    private void copy(File file, File outputFolder)
    {
        try {
            System.out.println("\tCopying [" + file + "] to folder [" + outputFolder + "]...");
            InputStream input = new FileInputStream(file);
            OutputStream out = new FileOutputStream(new File(outputFolder + File.separator + file.getName()));
            byte data[] = new byte[input.available()];
            input.read(data);
            out.write(data);
            out.flush();
            out.close();
            input.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private final class FileTypeOrFolderFilter implements FileFilter
    {
        private final String fileType;

        private FileTypeOrFolderFilter(String fileType)
        {
            this.fileType = fileType;
        }

        public boolean accept(File pathname)
        {
            return pathname.getName().endsWith("." + fileType) || pathname.isDirectory();
        }
    }
}

Use following file walker tree class to do that 使用以下文件沃克树类来做到这一点

static class TreeCopier implements FileVisitor<Path> {

        private final Path source;
        private final Path target;
        private final boolean preserve;
        private String []fileTypes;

        TreeCopier(Path source, Path target, boolean preserve, String []types) {
            this.source = source;
            this.target = target;
            this.preserve = preserve;
            this.fileTypes = types;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            // before visiting entries in a directory we copy the directory
            // (okay if directory already exists).
            CopyOption[] options = (preserve)
                    ? new CopyOption[]{COPY_ATTRIBUTES} : new CopyOption[0];

            Path newdir = target.resolve(source.relativize(dir));
            try {
                Files.copy(dir, newdir, options);
            } catch (FileAlreadyExistsException x) {
                // ignore
            } catch (IOException x) {
                System.err.format("Unable to create: %s: %s%n", newdir, x);
                return SKIP_SUBTREE;
            }
            return CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            String fileName = file.toFile().getName();
            boolean correctType = false;
            for(String t: fileTypes) {
                if(fileName.endsWith(t)){
                    correctType = true;
                    break;
                }
            }
            if(correctType)
                copyFile(file, target.resolve(source.relativize(file)), preserve);
            return CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
            // fix up modification time of directory when done
            if (exc == null && preserve) {
                Path newdir = target.resolve(source.relativize(dir));
                try {
                    FileTime time = Files.getLastModifiedTime(dir);
                    Files.setLastModifiedTime(newdir, time);
                } catch (IOException x) {
                    System.err.format("Unable to copy all attributes to: %s: %s%n", newdir, x);
                }
            }
            return CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) {
            if (exc instanceof FileSystemLoopException) {
                System.err.println("cycle detected: " + file);
            } else {
                System.err.format("Unable to copy: %s: %s%n", file, exc);
            }
            return CONTINUE;
        }


        static void copyFile(Path source, Path target, boolean preserve) {
            CopyOption[] options = (preserve)
                    ? new CopyOption[]{COPY_ATTRIBUTES, REPLACE_EXISTING}
                    : new CopyOption[]{REPLACE_EXISTING};
            if (Files.notExists(target)) {
                try {
                    Files.copy(source, target, options);
                } catch (IOException x) {
                    System.err.format("Unable to copy: %s: %s%n", source, x);
                }
            }
        }

    }

and call it using following two lines 并使用以下两行调用它

String []types = {".java", ".form"};
                TreeCopier tc = new TreeCopier(src.toPath(), dest.toPath(), false, types);
                Files.walkFileTree(src.toPath(), tc);

.java and .form file types are not omitted to copy and passed as String array parameter, src.toPath() and dest.toPath() are source and destination paths, false is used to specify not to preserve previous files and overwrite them if you want reverse that is to consider only these remove not and use as 复制并传递.java和.form文件类型,因为String数组参数,src.toPath()和dest.toPath()是源路径和目标路径,false用来指定不保留以前的文件并在以下情况下覆盖它们你想反向就是只考虑这些去除而不是用作

if(!correctType)

Use a FileFilter when listing files. 列出文件时使用FileFilter

In this case, the filter would select directories and any file type of interest. 在这种情况下,过滤器将选择目录和感兴趣的任何文件类型。


Here is a quick example (crudely hacked out of another project) of gaining a list of types of files in a directory structure. 这是一个获取目录结构中文件类型列表的快速示例(从另一个项目中砍掉了)。

import java.io.*;
import java.util.ArrayList;

class ListFiles {

    public static void populateFiles(File file, ArrayList<File> files, FileFilter filter) {
        File[] all = file.listFiles(filter);

        for (File f : all) {
            if (f.isDirectory()) {
                populateFiles(f,files,filter);
            } else {
                files.add(f);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        String[] types = {
            "java",
            "class"
        };
        FileFilter filter = new FileTypesFilter(types);
        File f = new File("..");
        ArrayList<File> files = new ArrayList<File>();
        populateFiles(f, files, filter);

        for (File file : files) {
            System.out.println(file);
        }
    }
}

class FileTypesFilter implements FileFilter {

    String[] types;

    FileTypesFilter(String[] types) {
        this.types = types;
    }

    public boolean accept(File f) {
        if (f.isDirectory()) return true;
        for (String type : types) {
            if (f.getName().endsWith(type)) return true;
        }
        return false;
    }
}

Take a look at the listFiles methods from the File class: 看一下File类中的listFiles方法:

Link 1 链接1

Link 2 连结2

You could try this code: 您可以尝试以下代码:

public class MyFiler implements FileNameFilter{

  bool accept(File file, String name){
     if(name.matches("*.jpg");
  }

}    


public void MassCopy(){
  ArrayList<File> filesToCopy = new ArrayList<File>();
  File sourceDirectory = new File("D:/Pictures/Holidays");
  String[] toCopy = sourceDirectory.list(new MyFilter());
  for(String file : toCopy){
    copyFileToDestination(file);
  }

 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何复制目录及其子目录,文件和zip文件 - How to copy a directory with its sub directories , files and zip files 将目录,子目录和文件复制到SD卡-Android - Copy directory ,sub directories and files to sd card - android 如何列出目录及其所有子目录中的所有文件 - How to list all files within a directory and all its sub-directories 如何从给定模式的目录和子目录中获取所有文件 - How to get all files from directory and sub directory with a given pattern 读取目录中的所有文件,包括其子目录 - Reading all files in a directory including its sub directories 如何将Jar中的资源目录以及所有包含的文件和子文件夹复制到另一个目录中 - How to copy a resource directory and all included files and sub-folders in a Jar onto another directory 番石榴如何将所有文件从一个目录复制到另一个目录 - Guava how to copy all files from one directory to another 如何读取文件夹和子目录中所有文件的内容 - How to read content of all files in the folder and in the sub directories 将所有文件从目录复制到另一个目录 - Copy all the files from a directory to another 递归监视Java中的目录和所有子目录 - Recursively monitor a directory and all sub directories in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM