简体   繁体   中英

Read files and merge them JavaFX

I need to read only .txt files from folder and subfolders and merge them into one file. The problem is when i set filter, it iterate only in root folder. Here is code:

public void walk( String path ) {
    FilenameFilter textFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".txt");
        }
    };
    File root = new File(path);
    File[] list = root.listFiles(textFilter);

    if (list == null) return;

    for ( File f : list ) {
        if ( f.isDirectory() ) {
            walk( f.getAbsolutePath() );
            System.out.println( "Dir:" + f.getAbsoluteFile() );

        }
        else {
            System.out.println( "File:" + f.getAbsoluteFile()              
            );
        }
    }
}

and DirectoryChooser function:

 DirectoryChooser directoryChooser  = new DirectoryChooser();
    directoryChooser.setTitle("Open Folder");
    File selectedDirectory =
            directoryChooser.showDialog(null);
    if(selectedDirectory == null){
        pathLabel.setText("No Directory selected");
    }else{
        pathLabel.setText(selectedDirectory.getAbsolutePath());
    }
    walk(selectedDirectory.getAbsolutePath());
}

What do i do wrong?

Consider using the java.nio.Files API instead. It has some predefined methods for walking through file trees:

public void walk(String path) {
    try (Stream<Path> allFiles = Files.walk(Paths.get(path))) {
        allFiles.filter(path -> path.toString().endsWith(".txt"))
            .forEach(System.out::println);
    }
}

You are filtering before looping and your filter excludes everything except of txt files. This means list does not contain subdirectories! Rather it only contains txt files. Consequently, your loops recursion does not work as expected, as the if(f.isDirectory()) branch is never executed.

Here is a small walking example of what you try to achieve:

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<File> results  = new ArrayList<>();
        walk(new File("/home/lwi/Documents"),results);

        System.out.println(results.size());

    }

    public static void walk(File dir, List<File> accum) {
        File[] files = dir.listFiles();

        if (files == null)
            return;

        for (File f : files) {
            if (f.isDirectory())
                walk(f, accum);
            else if (isTextFile(f))
                accum.add(f);
        }
    }

    private static boolean isTextFile(File f) {
        return f.getName().toLowerCase().endsWith(".txt");
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM