Learning Java
Custom Search

Previous Next

Part D - File I/O - Add Code to Select Files

In this part, we will add code to select which files to select. In the previous code, we only selected files that had ".java" in the name. We ignored what the user entered in txtFileSel.

In the field, txtFileSel, the user will be allowed to enter multiple (up to 10) substrings to use to compare against filenames. These will be separated by semicolons. The program will only select filenames where this substring can be found as part of the filename. If the program is used to search non-text files such as .class, .wav, .mp3, and .exe, the program can behave badly because our method, FileReader, is designed only for character reading.

The class called StringTokenizer can be used to help us separate the substrings entered by the user. To use it, we will have to import java.util.StringTokenizer.

We select which files in our actionPerformed method, so we will add the following variables. The array FileTypeChoices will be where we will place each of our file select substrings, up to 10. We will use numChoices to count how many choices the user entered. We will use maxChoices to make sure we don't allow the user to use more than 10 substrings.

    String[] FileTypeChoices = new String[10];
    int numChoices = 0;
    int maxChoices = 10;

In our actionPerformed method, we will use our class, StringTokenizer, to define a variable called st. With this, we will get the list of file types by using txtFileSel.getText() and specify that we expect these substrings to be separate with the character ";". Before we start loading our array, FileTypeChoices[], we have to empty it in case it contained something from a previous search. We do this in a "for" loop using k for indexing.

Then in our "while" loop we will pick up each substring using the method st.nextToken() and load it into an element of our array FileTypeChoices[]. When the method st.hasMoreTokens() returns false, we will know that there are no more tokens or substrings to process.

This snippet of code looks like this.

	StringTokenizer st = 
		new StringTokenizer(txtFileSel.getText(), ";");
	numChoices = 0;
	for (int k = 0; k < maxChoices; k++) 
	    FileTypeChoices[k] = "";

	while (st.hasMoreTokens()) {
	    FileTypeChoices[numChoices++] = st.nextToken();
        }

We will change the following code that makes sure that this file is not a directory and then makes sure the filename contains ".java".

                if (contents[i].isDirectory() == true) 
                    	continue;

		if (name.indexOf(".java") != -1)
		    SrchFile(name);	

The changed code will still make sure that the file is not a directory. However, now it will loop through the substrings in FileTypeChoices[] to compare with the filename stored in "name". The indexOf method gives the position where it found the substring. If it did not find that substring, indexOf will return -1.

                if (contents[i].isDirectory() == true) 
                    	continue;

		for (int j = 0; j < numChoices; j++) {
		    if (name.indexOf(FileTypeChoices[j]) != -1)
			SrchFile(name);
		}

Compile and test what we have covered in this part, which follows.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.StringTokenizer;

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) {
    String[] FileTypeChoices = new String[10];
    int numChoices = 0;
    int maxChoices = 10;

        Object source = evt.getSource();
        if (source == btnExit) {
	    System.exit(0);
	} else if (source == btnClear) {
	    txtResults.setText("");
	    str1 = "";
	    return;
	}

	StringTokenizer st = 
		new StringTokenizer(txtFileSel.getText(), ";");
	numChoices = 0;
	for (int k = 0; k < maxChoices; k++) 
	    FileTypeChoices[k] = "";

	while (st.hasMoreTokens()) {
	    FileTypeChoices[numChoices++] = st.nextToken();
        }

        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;

		for (int j = 0; j < numChoices; j++) {
		    if (name.indexOf(FileTypeChoices[j]) != -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

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved