|
Previous Next
Part C - File I/O - Add File Search
In this part, we will add code to perform the file search.
To access files, we will need to import the packages import java.io.*.
The class called File can represent files or directories. From the File class, we will instantiate an object called folder to represent our directory to be searched. In our constructor, we will use "." to pick up the current directory from which we are executing our class.
File folder = new File(".");
We will add the String DirToSearch to place the full name of the path into our text field so our user doesn't have to key it in. We'll set the text in txtDirectory before it is added to pane. The user can edit this field if they want to search another directory.
String DirToSearch;
DirToSearch = folder.getAbsolutePath();
txtDirectory.setText(DirToSearch);
In the actionPerformed method, we will add logic for when our button btnSearch is clicked. We currently have "if" statements for btnExit and btnClear. We will not bother with adding an "if" statement for btnSearch since if the first 2 are not satisfied, btnSearch is the only object left. So the fall through code will be for btnSearch.
We will load the variable folder with the directory entered by our user with the following:
folder = new File(txtDirectory.getText());
The following line creates the array called contents and loads it with the list of files and directories found in the requested directory.
File[] contents = folder.listFiles();
The File method, getName, will load the String name with the current element in contents[i] as we loop through the for loop. If the test, contents[i].isDirectory() is true, meaning we have a directory, we will skip to the next element in contents. If the test is false, then we have a file. Then we will test to see if this filename contains ".java". If it does, we will search thru this file by calling method SrchFile(name). In the next part, we will see if the filename contains what the user entered in txtFileSel.
Using the class File with its methods can throw exceptions which we must handle in a try / catch construct. To simplify it, we will just catch the all inclusive "Exception" exception. If it should occur, we will display the error in the MS Window cmd using System.out.println and we will display it in our application in the txtResults area by accumulating it in our variable str1. We will display a number with it to distinguish it from another error that can occur somewhere else in the program. That will aid in debugging, letting us know from which area of the code it occurred.
Finally, after looping thru all of the files in contents[], we will display our accumulations using txtResults.setText(str1).
This snippet of code looks like this.
try {
folder = new File(txtDirectory.getText());
File[] contents = folder.listFiles();
for (int i = 0; i < contents.length; i++) {
String name = contents[i].getName();
if (contents[i].isDirectory() == true)
continue;
if (name.indexOf(".java") != -1)
SrchFile(name);
}
} catch (Exception e) {
System.out.println("Error 101 -- " + e.toString());
str1 = str1 + " "
+ "Error 101 -- " + e.toString() + "\n";
}
txtResults.setText(str1);
Now let's put together the code for the method SrchFile.
We will define the Boolean variable WriteFname to prevent us from writing the same file name more than once.
We will need to combine the filename and its directory for FileReader. The problem is that the pathname we get in folder.getAbsolutePath() has a period behind it. So we will use substring to pick up all but the last byte. This occurs before the object txtDirectory is added to pane.
DirToSearch = DirToSearch.substring(0, (DirToSearch.length() - 1));
The class that will allow us to read our file is FileReader. With it we will define filex. Then from it, we will define buff using class BufferedReader. Buffering the read process is more efficient. After defining buff, we can use the method readLine() to get each line in our file. Whenever line is null (or empty), we will set our eof (end of file) flag to true. While the eof is false, we will process each line of the file.
The String method, line.indexOf(txtRequest.getText()), will search for our txtRequest in the line. The indexOf returns the position of the first instance of txtRequest.getText(). If that position is -1, we didn't find what we were looking for. So, if it is not -1 we will write the filename and the line by adding these to str1
This snippet of code looks like this.
public void SrchFile(String fname) {
boolean WriteFname = true;
try {
FileReader filex =
new FileReader(txtDirectory.getText() + fname);
BufferedReader buff = new BufferedReader(filex);
boolean eof = false;
while (!eof) {
String line = buff.readLine();
if (line == null)
eof = true;
else if (line.indexOf(txtRequest.getText()) != -1) {
if (WriteFname)
str1 = str1 + "File = " + fname + "\n";
str1 = str1 + " " + line + "\n";
WriteFname = false;
}
}
buff.close();
} catch (Exception e) {
System.out.println("Error 102 -- " + e.toString());
str1 = str1 + " "
+ "Error 102 -- " + e.toString() + "\n";
}
}
Compile and test what we have so far, which follows. Don't forget to make sure that when you put in your search argument, there is no space behind it.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Searcher extends JFrame implements ActionListener {
File folder = new File(".");
String DirToSearch;
String str1 = "";
JLabel lblRequest = new JLabel("Enter search argument:");
JTextField txtRequest = new JTextField(" ", 40);
JLabel lblDirectory = new JLabel("Enter the directory:");
JTextField txtDirectory = new JTextField(" ", 40);
JLabel lblFileSel =
new JLabel("Enter file extensions, separate with ;");
JTextField txtFileSel = new JTextField(".txt;.java;.htm", 40);
JLabel lblResults = new JLabel("Results:");
JTextArea txtResults = new JTextArea(15, 40);
JButton btnSearch = new JButton("Search");
JButton btnClear = new JButton("Clear");
JButton btnExit = new JButton("Exit");
public Searcher() {
super("File Search Application");
setSize(475, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
FlowLayout flow1 = new FlowLayout(FlowLayout.LEFT);
pane.setLayout(flow1);
JScrollPane scrollp = new JScrollPane(txtResults,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
pane.add(lblRequest);
pane.add(txtRequest);
DirToSearch = folder.getAbsolutePath();
DirToSearch = DirToSearch.substring
(0, (DirToSearch.length() - 1));
txtDirectory.setText(DirToSearch);
pane.add(lblDirectory);
pane.add(txtDirectory);
pane.add(lblFileSel);
pane.add(txtFileSel);
pane.add(lblResults);
pane.add(scrollp);
btnSearch.addActionListener(this);
btnClear.addActionListener(this);
btnExit.addActionListener(this);
pane.add(btnSearch);
pane.add(btnClear);
pane.add(btnExit);
setContentPane(pane);
setVisible(true);
}
public static void main(String[] arguments) {
Searcher doSearch = new Searcher();
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source == btnExit) {
System.exit(0);
} else if (source == btnClear) {
txtResults.setText("");
str1 = "";
return;
}
try {
folder = new File(txtDirectory.getText());
File[] contents = folder.listFiles();
for (int i = 0; i < contents.length; i++) {
String name = contents[i].getName();
if (contents[i].isDirectory() == true)
continue;
if (name.indexOf(".java") != -1)
SrchFile(name);
}
} catch (Exception e) {
System.out.println("Error 101 -- " + e.toString());
str1 = str1 + " "
+ "Error 101 -- " + e.toString() + "\n";
}
txtResults.setText(str1);
}
public void SrchFile(String fname) {
boolean WriteFname = true;
try {
FileReader filex =
new FileReader(txtDirectory.getText() + fname);
BufferedReader buff = new BufferedReader(filex);
boolean eof = false;
while (!eof) {
String line = buff.readLine();
if (line == null)
eof = true;
else if (line.indexOf(txtRequest.getText()) != -1) {
if (WriteFname)
str1 = str1 + "File = " + fname + "\n";
str1 = str1 + " " + line + "\n";
WriteFname = false;
}
}
buff.close();
} catch (Exception e) {
System.out.println("Error 102 -- " + e.toString());
str1 = str1 + " "
+ "Error 102 -- " + e.toString() + "\n";
}
}
}
Previous Next
|