Learning Java
Custom Search

Previous Home

Part E - File I/O - Save Results to a Files

In this final part, we will save the results of our search to a file called SaveSearch.txt in our current directory. If desired, this can be enhanced by adding a text field where the user can enter their own filename.

We will add another button and add it to pane placing the following in the obvious places.

	JButton btnSave = new JButton("Save");
	btnSave.addActionListener(this);
        pane.add(btnSave);

In our actionPerformed method, we need to test for this new button. If it was pressed we will call a new method called SaveResults to do the savings. The code would be too cumbersome to add here in the middle of the "if", so we will place it in a method called SaveResults which will make it easier to understand.

	  else if (source == btnSave) {
	    SaveResults();
	    return;
	}

Our new method, SaveResults, will look like the following. The FileWriter class is a class that lets us write to character files, in this case, our output file SaveSearch.txt. The BufferedWriter class will make this writing more efficient by allowing us to buffer our output. After we write our entire results in str1, then we must close the file and free that resource. We have to place this in a try / catch construct because we must handle any file processing errors.

Use MS Write to view this file instead of Notepad. To better view with Notepad, change all line feeds, "\n", to carriage returns and line feeds, "\r\n".

    public void SaveResults() {
        try {
	    FileWriter filew = new FileWriter(txtDirectory.getText() 
		+ "SaveSearch.txt");
	    BufferedWriter buffw = new BufferedWriter(filew);

	    buffw.write(str1);
            buffw.close(); 

        } catch (Exception e) {
            System.out.println("Error 103 -- " + e.toString());
	    str1 = str1 + "       " 
			+ "Error 103 -- " + e.toString() + "\n";
        }
    }

Compile and test the final version, 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 btnSave = new JButton("Save");
    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);
	btnSave.addActionListener(this);
	btnExit.addActionListener(this);
        pane.add(btnSearch);
        pane.add(btnClear);
        pane.add(btnSave);
        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;
	} else if (source == btnSave) {
	    SaveResults();
	    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";
        }
    }

    public void SaveResults() {
        try {
	    FileWriter filew = new FileWriter(txtDirectory.getText() 
		+ "SaveSearch.txt");
	    BufferedWriter buffw = new BufferedWriter(filew);

	    buffw.write(str1);
            buffw.close(); 

        } catch (Exception e) {
            System.out.println("Error 103 -- " + e.toString());
	    str1 = str1 + "       " 
			+ "Error 103 -- " + e.toString() + "\n";
        }
    }
}

 

Previous Home

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved