我想创建一个程序,它将在选定目录(例如:“ C:/”)中找到包含某个单词的所有文本文件。
[我想说:例如,我在“ C:/”中有三个文本文件,里面有文本。
1.txt Hello world this is test
2.txt Goodbye bla bla bla
3.txt Hello 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;
}
}
遍历文件
如果您使用的是Java7,请使用Files.walkFileTree(args)
行走树:doc
如果您使用的是Java 7以下版本,请递归使用File.listFiles()
。
查找文件
使用Scanner.findWithinHorizon(字符串模式,int horizon)查找所需的任何正则表达式: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
这是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() );
}