I want to create a program that will find all the text files in a selected directory (for ex.: "C:/") that contain a certain word.
I want to say: for ex., I have in "C:/", three text files with text inside.
1.txt Hello world this is test
2.txt Goodbye bla bla bla
3.txt Hello my name is John
If I type the word "Hello", the program must find 1.txt and 3.txt
What can you recommend for me? What commands can help me here? Thank you for answers.
UPDATE: For now I have only code to select directory:
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;
}
}
Iterating over the files
If you are on Java7 use the Files.walkFileTree(args)
to walk the tree: doc
If you are on Java below version 7 just use File.listFiles()
recursively.
Finding in a file
Use Scanner.findWithinHorizon(String pattern, int horizon) to find whatever regexp you want: doc
Here is an example of how you could do it:
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;
}
you could use the method in your code like this:
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
Here is an example in java 8 thats streams not recursive
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() );
}
来源:https://stackoverflow.com/questions/13858966/search-files-by-text-content-inside