我想创建一个程序来查找包含某个单词的所选目录中的所有文本文件(例如:" 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;
}
}
答案 0 :(得分:5)
迭代文件
如果您使用的是Java7,请使用Files.walkFileTree(args)
走树:doc
如果您使用的是低于版本7的Java,请以递归方式使用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
答案 1 :(得分: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() );
}