1

我想创建一个程序,该程序将在包含特定单词的选定目录(例如:“C:/”)中查找所有文本文件。

我想说:例如,我在“C:/”中有三个文本文件,里面有文本。

1.txtHello world this is test

2.txtGoodbye bla bla bla

3.txtHello my name is John

如果我输入单词“Hello”,程序必须找到 1.txt 和 3.txt

你有什么可以推荐给我的?什么命令可以在这里帮助我?谢谢你的回答。

更新:现在我只有选择目录的代码:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;


public class SelectDirectory extends JPanel implements ActionListener {
    JButton go;

    JFileChooser chooser;
    String choosertitle;

    public SelectDirectory() {
        go = new JButton("Select directory: ");
        go.addActionListener(this);
        add(go);
    }

    public void actionPerformed(ActionEvent e) {
        chooser = new JFileChooser(); 
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle(choosertitle);
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(true);

        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
            System.out.println("getCurrentDirectory(): " + 
                                chooser.getCurrentDirectory());
            System.out.println("getSelectedFile() : " +  chooser.getSelectedFile());
            //
            //
            //
            searchFiles(); // error here, I dont know really how to use this method
            //
            //
            //
        } 
        else {
            System.out.println("No Selection ");
        }
    }

    public Dimension getPreferredSize(){
        return new Dimension(200, 200);
    }

    public static void main(String s[]) {
        JFrame frame = new JFrame("");
        SelectDirectory panel = new SelectDirectory();
        frame.addWindowListener(
            new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            }
        );
        frame.getContentPane().add(panel,"Center");
        frame.setSize(panel.getPreferredSize());
        frame.setVisible(true);
    }

    private ArrayList<String> searchFiles(File file, String pattern, 
                        ArrayList<String> result) throws FileNotFoundException {

        if (!file.isDirectory()) {
            throw new IllegalArgumentException("file has to be a directory");
        }

        if (result == null) {
            result = new ArrayList<String>();
        }

        File[] files = file.listFiles();

        if (files != null) {
            for (File currentFile : files) {
                if (currentFile.isDirectory()) {
                    searchFiles(currentFile, pattern, result);
                } else {
                    Scanner scanner = new Scanner(currentFile);
                    if (scanner.findWithinHorizon(pattern, 0) != null) {
                        result.add(currentFile.getName());
                    }
                    scanner.close();
                }
            }
        }
        return result;
    }
}
4

2 回答 2

7

遍历文件

如果您使用的是 Java7,请使用Files.walkFileTree(args)遍历树:doc

如果您使用的是版本 7 以下的 Java,只需File.listFiles()递归使用。

在文件中查找

使用 Scanner.findWithinHorizo​​n(String pattern, int horizo​​n) 查找您想要的任何正则表达式: doc

这是一个如何做到这一点的示例:

private List<String> searchFiles(File file, String pattern, List<String> result) throws FileNotFoundException {

    if (!file.isDirectory()) {
        throw new IllegalArgumentException("file has to be a directory");
    }

    if (result == null) {
        result = new ArrayList<String>();
    }

    File[] files = file.listFiles();

    if (files != null) {
        for (File currentFile : files) {
            if (currentFile.isDirectory()) {
                searchFiles(currentFile, pattern, result);
            } else {
                Scanner scanner = new Scanner(currentFile);
                if (scanner.findWithinHorizon(pattern, 0) != null) {
                    result.add(currentFile.getName());
                }
                scanner.close();
            }
        }
    }
    return result;
}

您可以像这样在代码中使用该方法:

 File folder = selectedFile.isDirectory() ? selectedFile : currentDirectory;
 ArrayList<String> files = new ArrayList<String>();
 try {
    files = searchFiles(folder, "Hello", files);
 } catch (FileNotFoundException e1) {
    // you should tell the user here that something went wrong
 }
 // 'files' now contains the resulting file names 
于 2012-12-13T12:04:11.023 回答
0

这是 java 8 中的一个示例,它的流不是递归的

try( Stream<Path> walk = Files.walk( Paths.get( SRC ) ) ) {
        final String regex = "someregex";
        List<String> filesContainingRegex = walk.filter( path -> !Files.isDirectory( path ) ).flatMap( path -> {
            try {
                File file = path.toFile();
                Scanner scanner = new Scanner( file );
                if( scanner.findWithinHorizon( regex, 0 ) != null ) {
                    scanner.close();
                    return Stream.of( path.getFileName().toString() );
                }
                scanner.close();
            } catch( FileNotFoundException fnfe ) {
                System.out.println( fnfe.getMessage();
            }
            return Stream.empty();
        } ).collect( Collectors.toList() );
    }
于 2019-10-25T18:22:15.893 回答