Results 1 to 1 of 1
- 05-01-2011, 07:23 PM #1
Member
- Join Date
- May 2011
- Posts
- 3
- Rep Power
- 0
Searching through a directory of files and reading contents
I am new to java and I am having a problem with some code. I am trying to create a java GUI whereby users enter a piece of text to search and a folder to search. The code will then search iteratively through each file for the text and append the results in a jtextarea. My search works for just one file if I exclude the loop through the files. When looping it does not produce any errors but I receive no output. My code is:
package searchfile;
import java.io.*;
import javax.swing.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.DateFormat;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Darren Biggs
*/
public class SearchFileGUI extends javax.swing.JFrame {
/** Creates new form SearchFileGUI */
public SearchFileGUI() {
initComponents();
}
//used to create method to search from a file.
public static CharSequence fromFile(String filename) throws IOException
{
FileInputStream fileinputstream = new FileInputStream(filename);
FileChannel filechannel = fileinputstream.getChannel();
ByteBuffer bytebuffer = filechannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) filechannel.size());
CharBuffer charbuffer = Charset.forName("8859_1").newDecoder().decode(byte buffer);
return charbuffer;
}
//used to create a method to search from a folder, is effectively the same as for file.
public static CharSequence fromFolder(String filename) throws IOException
{
FileInputStream fileinputstream = new FileInputStream(filename);
FileChannel filechannel = fileinputstream.getChannel();
ByteBuffer bytebuffer = filechannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) filechannel.size());
CharBuffer charbuffer = Charset.forName("8859_1").newDecoder().decode(byte buffer);
return charbuffer;
}
/** This method is called from within the constructor to
* initialise the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
searchText = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
fileLocation = new javax.swing.JTextField();
searchButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
outputScreen = new javax.swing.JTextArea();
clearButton = new javax.swing.JButton();
saveButton = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();
menuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
openMenuItem = new javax.swing.JMenuItem();
saveMenuItem = new javax.swing.JMenuItem();
saveAsMenuItem = new javax.swing.JMenuItem();
exitMenuItem = new javax.swing.JMenuItem();
editMenu = new javax.swing.JMenu();
cutMenuItem = new javax.swing.JMenuItem();
copyMenuItem = new javax.swing.JMenuItem();
pasteMenuItem = new javax.swing.JMenuItem();
deleteMenuItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
contentsMenuItem = new javax.swing.JMenuItem();
aboutMenuItem = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);
jLabel1.setText("Enter Text to search:");
jLabel2.setText(" Search a File for Key Words or Phrases");
jLabel2.setHorizontalTextPosition(javax.swing.Swin gConstants.CENTER);
searchText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchTextActionPerformed(evt);
}
});
jLabel3.setText("Enter File name and Location:");
searchButton.setText("SEARCH");
searchButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchButtonActionPerformed(evt);
}
});
outputScreen.setColumns(20);
outputScreen.setRows(5);
jScrollPane1.setViewportView(outputScreen);
clearButton.setText("CLEAR");
clearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearButtonActionPerformed(evt);
}
});
saveButton.setText("SAVE");
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt);
}
});
jButton1.setText("Search Folder");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
fileMenu.setText("File");
openMenuItem.setText("Open");
fileMenu.add(openMenuItem);
saveMenuItem.setText("Save");
fileMenu.add(saveMenuItem);
saveAsMenuItem.setText("Save As ...");
fileMenu.add(saveAsMenuItem);
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed(evt);
}
});
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
editMenu.setText("Edit");
cutMenuItem.setText("Cut");
editMenu.add(cutMenuItem);
copyMenuItem.setText("Copy");
editMenu.add(copyMenuItem);
pasteMenuItem.setText("Paste");
editMenu.add(pasteMenuItem);
deleteMenuItem.setText("Delete");
editMenu.add(deleteMenuItem);
menuBar.add(editMenu);
helpMenu.setText("Help");
contentsMenuItem.setText("Contents");
helpMenu.add(contentsMenuItem);
aboutMenuItem.setText("About");
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILI NG, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADIN G, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.TRAILING, false)
.addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(45, 45, 45)
.addComponent(searchButton)))
.addGap(34, 34, 34)
.addComponent(jButton1)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.Component Placement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.LEADING, false)
.addComponent(fileLocation)
.addComponent(searchText, javax.swing.GroupLayout.DEFAULT_SIZE, 205, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGap(57, 57, 57)
.addComponent(clearButton)
.addPreferredGap(javax.swing.LayoutStyle.Component Placement.RELATED, 27, Short.MAX_VALUE)
.addComponent(saveButton)
.addGap(36, 36, 36))))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILI NG, layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(100, 100, 100))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(13, 13, 13)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(fileLocation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.BASELINE)
.addComponent(searchButton)
.addComponent(jButton1)
.addComponent(clearButton)
.addComponent(saveButton))
.addGap(11, 11, 11)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void exitMenuItemActionPerformed(java.awt.event.ActionE vent evt) {
System.exit(0);
}
private void searchButtonActionPerformed(java.awt.event.ActionE vent evt) {
//runs the method to search through a single file, this works!
DoSearchFile();
}
private void clearButtonActionPerformed(java.awt.event.ActionEv ent evt) {
//Clears the content of the jtextarea.
outputScreen.setText("");
}
private void searchTextActionPerformed(java.awt.event.ActionEve nt evt) {
}
private void saveButtonActionPerformed(java.awt.event.ActionEve nt evt) {
//Runs the method to save the contents of the jtextarea to file.
DoSaveSearch();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//Runs the method to search through the files in a folder, this does not work yet!
DoSearchFolder();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SearchFileGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem aboutMenuItem;
private javax.swing.JButton clearButton;
private javax.swing.JMenuItem contentsMenuItem;
private javax.swing.JMenuItem copyMenuItem;
private javax.swing.JMenuItem cutMenuItem;
private javax.swing.JMenuItem deleteMenuItem;
private javax.swing.JMenu editMenu;
private javax.swing.JMenuItem exitMenuItem;
private javax.swing.JTextField fileLocation;
private javax.swing.JMenu fileMenu;
private javax.swing.JMenu helpMenu;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenuItem openMenuItem;
private javax.swing.JTextArea outputScreen;
private javax.swing.JMenuItem pasteMenuItem;
private javax.swing.JMenuItem saveAsMenuItem;
private javax.swing.JButton saveButton;
private javax.swing.JMenuItem saveMenuItem;
private javax.swing.JButton searchButton;
private javax.swing.JTextField searchText;
// End of variables declaration
//Method to save content of jtextarea to file, works!
public void DoSaveSearch() {
String fileData;
try {
File saveToDirectory1 = new File("c:\\DBNet");
if (saveToDirectory1.exists() == false) {
// It returns false if File or directory does not exist
saveToDirectory1.mkdir();}
File saveToDirectory2 = new File(saveToDirectory1 + "\\Logs");
if (saveToDirectory2.exists() == false) {
// It returns false if File or directory does not exist
saveToDirectory2.mkdir();}
File saveToFile = new File(saveToDirectory2 + "\\searchfilelog.txt");
if (saveToFile.exists() == false) {
// It returns false if File or directory does not exist
saveToFile.createNewFile();}
String mydate = DateFormat.getInstance().format(new Date());
fileData = (outputScreen.getText() + " " + mydate);
BufferedWriter saveFile = new BufferedWriter(new FileWriter(saveToFile, true));
saveFile.newLine();
saveFile.write(fileData);
saveFile.close();
JOptionPane.showMessageDialog(null, "Added data to text file");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Unable to add data to text file");
}
}
/*Method to search iteratively through a folder and check all files for
text search criteria - This is not working but yet produces no errors!
*/
public void DoSearchFolder(){
try {
/*This bit appears to work as I get the message if the directory
does not exist */
File folder = new File(fileLocation.getText());
String[] directory = folder.list();
if (directory == null){
JOptionPane.showMessageDialog(null, "This is not a directory or the directory does not exist");
} else {
/*From hear is where the problems seems to be, if only I got
errors! */
for (int i=0; i<directory.length; i++){
String listFilenames = directory[i];
Pattern pattern =
Pattern.compile(searchText.getText());
Matcher matcher =
pattern.matcher(fromFile(listFilenames));
boolean found = false;
while (matcher.find()) {
String group = matcher.group();
int start = matcher.start();
int end = matcher.end();
String endMatch = Integer.toString(end);
String startMatch = Integer.toString(start);
outputScreen.append("I found the text " + group + " starting at character " + startMatch + " and ending at character " + endMatch + " " + "from file " + listFilenames);
found = true;
}
if(!found){
JOptionPane.showMessageDialog(null, "No Match Found");
}}}
} catch (IOException e) {
}}
/*This method is for only one file and it works fine! */
public void DoSearchFile() {
try {
Pattern pattern =
Pattern.compile(searchText.getText());
String info=null;
info = fileLocation.getText();
File fileIn = new File(info);
if (fileIn.exists()) {
JOptionPane.showMessageDialog(null, "The file exists");
}
else {
JOptionPane.showMessageDialog(null, "The file does not exist");}
Matcher matcher =
pattern.matcher(fromFile(info));
boolean found = false;
while (matcher.find()) {
String group = matcher.group();
int start = matcher.start();
int end = matcher.end();
String endMatch = Integer.toString(end);
String startMatch = Integer.toString(start);
outputScreen.append("I found the text " + group + " starting at character " + startMatch + " and ending at character " + endMatch + " " + "\n");
found = true;
}
if(!found){
JOptionPane.showMessageDialog(null, "No Match Found");
}
} catch (IOException e) {
}
}
}
I have put comments in to show which sections work and which don't. Any help would be greatly appreciated.
Similar Threads
-
Listing directory contents
By gandalf5166 in forum New To JavaReplies: 8Last Post: 05-02-2010, 12:41 AM -
Help with reading / searching a .txt file
By Absolute in forum New To JavaReplies: 0Last Post: 03-11-2010, 05:39 AM -
How to read from all files in a directory & plot the contents?
By 123 in forum Java 2DReplies: 3Last Post: 02-10-2010, 07:22 PM -
opening directory (folder) to reveal contents.
By solris in forum New To JavaReplies: 6Last Post: 06-28-2009, 06:40 PM -
reading files from the server where the Directory listings are disabled
By sudukrish in forum Advanced JavaReplies: 0Last Post: 04-29-2009, 07:16 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks