我想创建一个程序,该程序将在包含特定单词的选定目录(例如:“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;
}
}