Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中递归处理多个子目录中的相同文件_Java - Fatal编程技术网

在Java中递归处理多个子目录中的相同文件

在Java中递归处理多个子目录中的相同文件,java,Java,嗨,我想用Java处理多个子目录中的文件。Psuedo代码将是 while(mainDir.hasMoreDirectory()) { getFilesFromCurrentDirectory() passThoseFilesAsArgumentToProcess() } 我目前正在使用以下代码 public void list(File file) { System.out.println(file.getName()); File[] children = fi

嗨,我想用Java处理多个子目录中的文件。Psuedo代码将是

while(mainDir.hasMoreDirectory())
{
   getFilesFromCurrentDirectory()
   passThoseFilesAsArgumentToProcess()
}
我目前正在使用以下代码

public void list(File file) {
    System.out.println(file.getName());
    File[] children = file.listFiles();
    for (File child : children) {
        list(child);
    }
}
上面的代码只列出了文件。我可以做的另一件事是,我必须将文件和目录列表存储在一个列表中,然后在另一个循环中进行处理。但我不能拿出我想要的伪代码。我是新的文件目录,请帮助。提前谢谢。

以下内容可以吗

public void list(File file) {
    File[] children = file.listFiles();

    if (children != null) {
        process(children);

        for (File child : children) {
            if (child.isDirectory()) {
                list(child);
            }
        }
    } else {
        process(new File[]{file});
    }
}

private void process(File[] children) {
    for (File child : children) {
        if (child.isFile()) {
            // process normal file
        }
    }
}
下面可以吗

public void list(File file) {
    File[] children = file.listFiles();

    if (children != null) {
        process(children);

        for (File child : children) {
            if (child.isDirectory()) {
                list(child);
            }
        }
    } else {
        process(new File[]{file});
    }
}

private void process(File[] children) {
    for (File child : children) {
        if (child.isFile()) {
            // process normal file
        }
    }
}

这样的方法将递归地返回目录中所有文件的
列表。您可以对返回的
列表进行操作
或替换
rtn。使用您的处理添加
调用

请注意,此方法无法阻止它陷入循环符号链接中

public static List<File> getFilesRecursive(File s)
{
    ArrayList<File> rtn = new ArrayList<File>();
    File[] contents = s.listFiles();
    for(int i = 0; i<contents.length; i++)
    {
        if(contents[i].isDirectory()){
            rtn.addAll(getFilesRecursive(contents[i]));
        }else{
            rtn.add(contents[i]);
        }
    }
    return rtn;
}
公共静态列表getFilesRecursive(文件s)
{
ArrayList rtn=新的ArrayList();
File[]contents=s.listFiles();

对于(int i=0;i这样的方法将递归返回目录中所有文件的
列表
。您可以对返回的
列表
进行操作,也可以用处理替换
rtn。添加
调用

请注意,此方法无法阻止它陷入循环符号链接中

public static List<File> getFilesRecursive(File s)
{
    ArrayList<File> rtn = new ArrayList<File>();
    File[] contents = s.listFiles();
    for(int i = 0; i<contents.length; i++)
    {
        if(contents[i].isDirectory()){
            rtn.addAll(getFilesRecursive(contents[i]));
        }else{
            rtn.add(contents[i]);
        }
    }
    return rtn;
}
公共静态列表getFilesRecursive(文件s)
{
ArrayList rtn=新的ArrayList();
File[]contents=s.listFiles();

对于(int i=0;i也许这段代码可以帮助您:

public void traverse(String path) {
    File root = new File(path);
    File[] list = root.listFiles();
    if (list == null) return;

    for (File file : list) {
        if (file.isDirectory()) {
            traverse(file.getAbsolutePath());
            System.out.println("Directory: " + file.getAbsoluteFile());
        } else {
            System.out.println("File: " + file.getAbsoluteFile());
        }
    }
}

也许这段代码可以帮助您:

public void traverse(String path) {
    File root = new File(path);
    File[] list = root.listFiles();
    if (list == null) return;

    for (File file : list) {
        if (file.isDirectory()) {
            traverse(file.getAbsolutePath());
            System.out.println("Directory: " + file.getAbsoluteFile());
        } else {
            System.out.println("File: " + file.getAbsoluteFile());
        }
    }
}
private static List allFiles=new ArrayList();
私有静态void进程文件(字符串根目录){
File rootDir=新文件(rootDirectory);
if(rootDir.exists()){
遍历目录(rootDir);
}
}
私有静态void遍历目录(文件){
//将所有文件和目录添加到列表中。
添加(文件);
if(file.isDirectory()){
File[]fileList=File.listFiles();
用于(文件句柄:文件列表){
遍历目录(fileHandle);
}
}否则{
//调用进程文件
System.out.println(“调用进程文件”+file.getAbsolutePath());
}
}
私有静态列表allFiles=new ArrayList();
私有静态void进程文件(字符串根目录){
File rootDir=新文件(rootDirectory);
if(rootDir.exists()){
遍历目录(rootDir);
}
}
私有静态void遍历目录(文件){
//将所有文件和目录添加到列表中。
添加(文件);
if(file.isDirectory()){
File[]fileList=File.listFiles();
用于(文件句柄:文件列表){
遍历目录(fileHandle);
}
}否则{
//调用进程文件
System.out.println(“调用进程文件”+file.getAbsolutePath());
}
}

如果您使用的是Java 7,则可以使用Files.walkFileTree方法的形式利用NIO的增强功能。在Java中,遍历文件系统从未如此容易

关于它的用法有一个简短的教程


它实现了访问者模式,因此您无需担心遍历算法本身,只需指定您希望对每个条目执行的操作。

如果您使用的是Java 7,则可以利用NIO的增强功能,即Files.walkFileTree方法。在Java中,遍历文件系统从来都不容易

关于它的用法有一个简短的教程


它实现了访问者模式,因此您无需担心遍历算法本身,只需指定您希望对每个条目执行的操作。

在Java 7中遍历目录树时,使用
路径
文件
功能。它们不仅简化了目录和文件的读取,而且比“旧”
文件
方式

假设您有两个目录:
mainDir
otherDir
,并且您希望遍历
mainDir
的所有目录,直到其叶子。对于
maiondir
中的每个条目(文件、子目录、符号链接等),您希望比较此条目及其属性(大小、修改时间等)针对
otherDir
中相同位置的条目。 那么这就是您的代码:

public final void test() throws IOException, InterruptedException {
    final Path mainDir = Paths.get("absolute path to your main directory to read from");
    final Path otherDir = Paths.get("absolute path to your other directory to compare");

    // Walk thru mainDir directory
    Files.walkFileTree(mainDir, new FileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path path,
                BasicFileAttributes atts) throws IOException {
            return visitFile(path, atts);
        }

        @Override
        public FileVisitResult visitFile(Path path, BasicFileAttributes mainAtts)
                throws IOException {
            // I've seen two implementations on windows and MacOSX. One has passed the relative path, one the absolute path.
            // This works in both cases
            Path relativePath = mainDir.relativize(mainDir.resolve(path));

            BasicFileAttributes otherAtts = Files.readAttributes(otherDir.resolve(relativePath), BasicFileAttributes.class);

            // Do your comparison logic here:
            compareEntries(mainDir, otherDir, relativePath, mainAtts, otherAtts);

            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path path,
                IOException exc) throws IOException {
            // TODO Auto-generated method stub
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path path, IOException exc)
                throws IOException {
            exc.printStackTrace();

            // If the root directory has failed it makes no sense to continue
            return (path.equals(mainDir))? FileVisitResult.TERMINATE:FileVisitResult.CONTINUE;
        }
    });
}
public final void test()抛出IOException、InterruptedException{
final Path mainDir=Path.get(“要读取的主目录的绝对路径”);
final Path otherDir=Path.get(“要比较的其他目录的绝对路径”);
//遍历mainDir目录
walkFileTree(mainDir,newfilevisitor()){
@凌驾
公共文件VisitResult preVisitDirectory(路径,
基本文件属性(atts)引发IOException{
返回visitFile(路径、附件);
}
@凌驾
公共文件VisitResult visitFile(路径路径,基本文件属性mainAtts)
抛出IOException{
//我在windows和MacOSX上看到了两个实现,一个通过了相对路径,一个通过了绝对路径。
//这在两种情况下都有效
路径相对路径路径=mainDir.relativize(mainDir.resolve(Path));
BasicFileAttributes otherAttts=Files.readAttributes(otherDir.resolve(relativePath)、BasicFileAttributes.class);
//在此处执行比较逻辑:
比较(主目录、其他目录、相对路径、主目录、其他目录);
返回FileVisitResult.CONTINUE;
}
@凌驾
公共文件VisitResult postVisitDirectory(路径,
IOException exc)抛出IOException{
//TODO自动生成的方法存根
返回FileVisitResult.CONTINUE;
}
@凌驾
公共文件VisitResult visitFileFailed(路径,IOException exc)
抛出IOException{
exc.printStackTrace();
//如果根