Java Forums

Main Menu
Home
Today's Posts
FAQ
Search
Contact Us

Java Network
Linux Archive
Java Tips
Java Tips Blog

Sponsored Links





Welcome to the Java Forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community, you will:

  • have access to post topics
  • communicate privately with other members (PM)
  • not see advertisements between posts
  • have the possibility to earn one of our surprises if you are an active member
  • access many other special features that will be introduced later.

Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact us.

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 04-11-2008, 11:29 PM
Member
 
Join Date: Apr 2008
Posts: 15
mark-mlt is on a distinguished road
Search in text file
Hello all, im trying to do a search in a text file. Can any tell me why its not working. thx. here is my code;

import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;

public class Layout {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
private static final Component btnGO = null;
private static JCheckBox commonWords;
private static TextField txtSearch;

public static void addComponentsToPane(Container pane) throws FileNotFoundException {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation. RIGHT_TO_LEFT);

}

JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;

}

TextField txtSearch;
txtSearch = new TextField("Click GO to Search");
if (shouldWeightX) {
c.weightx = 0.5;

}


c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(txtSearch, c);

final JLabel lblMsg = new JLabel();
pane.add(lblMsg, c);

JButton btnGO = new JButton("GO");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
ActionListener actionPerformed = null;
btnGO.addActionListener (actionPerformed);

pane.add(btnGO, c);

commonWords = new JCheckBox("Common Words");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 0;
pane.add(commonWords, c);

// //button = new JButton("Long-Named Button 4");
final JTextArea textArea = new JTextArea("", 4, 30);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
// textArea.

final JScrollPane sbrText;
sbrText = new JScrollPane(textArea);
sbrText.setVerticalScrollBarPolicy(JScrollPane.VER TICAL_SCROLLBAR_ALWAYS);

textArea.setAutoscrolls(true);

textArea.setLineWrap(true);
JScrollPane jScrollPane1;
jScrollPane1 = new JScrollPane(textArea);
textArea.setEditable(false);
// add(scrollPane, BorderLayout.CENTER);
pane.add(textArea, c);
pane.add(jScrollPane1, c);
String line;
sbrText.setVisible(true);
pane.add(sbrText, c);

Layout text; // this is the textarea you already have on your page
File theFile = new File ("Sentences.txt");
BufferedReader br = new BufferedReader (new FileReader ("Sentences.txt"));

try {
// String line;
while ((line = br.readLine()) != null) {
// final JTextArea textArea = null;
textArea.append (line);

}
} catch (IOException e) {
e.printStackTrace ();
JOptionPane.showConfirmDialog(null, "File not found.");
}
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
* @throws FileNotFoundException
*/

private static void createAndShowGUI() throws FileNotFoundException {
//Create and set up the window.
JFrame frame = new JFrame("File Reader");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);

//Set up the content pane.
addComponentsToPane(frame.getContentPane());
// addComponentsToPane(frame.sbrText.setVisible(true) );

//Display the window.
frame.setVisible(true);
//frame.sbrText.setVisible(true);
}


public void actionPerformed (ActionEvent event) {


System.out.println("yey clicked");
String s = txtSearch.getText();
if (s.length() <= 0) {
message("Nothing to search");
return;
}

String content = txtSearch.getText();
int index = content.indexOf(s, 0);
if (index >= 0) { // match found
try {
int end = index + s.length();
// hilit.addHighlight(index, end, painter);
txtSearch.setCaretPosition(end);
// entry.setBackground(entryBg);
message("'" + s + "' found.");
}
finally {
System.out.println("worked");
}
}
else {
// entry.setBackground(ERROR_COLOR);
message("'" + s + "' not found.");
}
}

void message(String msg) {
// lblMsg.setText(msg);
System.out.println(msg);
}

// DocumentListener methods





// public void search() {
// hilit.removeAllHighlights();


// class CancelAction extends AbstractAction {
// public void actionPerformed(ActionEvent ev) {
// hilit.removeAllHighlights();
// entry.setText("");
// entry.setBackground(entryBg); btnGO.addActionListener(this);

// }
// }




public static void main(String[] args) {

//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
createAndShowGUI();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}

File file = new File("C:\\Documents and Settings\\Administrator.MYCOMPUTER\\My Documents\\School Documents\\IAD\\Assignments\\Java\\English Sentences\\Java Sentences.txt");
StringBuffer contents = new StringBuffer();
BufferedReader reader = null;

try
{
reader = new BufferedReader(new FileReader(file));
String text = null;

// repeat until all lines is read
while ((text = reader.readLine()) != null)
{
contents.append(text)
.append(System.getProperty(
"line.separator"));
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (reader != null)
{
reader.close();
}
} catch (IOException e)
{
e.printStackTrace();
JOptionPane.showConfirmDialog(null, "File not found.");

}
}
}

});
};


protected static void lblMsg(String string) {
// TODO Auto-generated method stub

}




public static JCheckBox getCommonWords() {
return commonWords;
}




public static void setCommonWords(JCheckBox commonWords) {
Layout.commonWords = commonWords;
}




public static TextField getTxtSearch() {
return txtSearch;
}




public static void setTxtSearch(TextField txtSearch) {
Layout.txtSearch = txtSearch;
}


public static boolean isShouldFill() {
return shouldFill;
}




public static boolean isShouldWeightX() {
return shouldWeightX;
}




public static boolean isRIGHT_TO_LEFT() {
return RIGHT_TO_LEFT;
}




public static Component getBtnGO() {
return btnGO;
}

}
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 04-11-2008, 11:38 PM
Member
 
Join Date: Feb 2008
Posts: 45
new_2_java is on a distinguished road
What's the error that you are getting?
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 04-11-2008, 11:43 PM
Member
 
Join Date: Apr 2008
Posts: 15
mark-mlt is on a distinguished road
ermmm no errors... my problem is at the event handler i think ...
Bookmark Post in Technorati
Reply With Quote
  #4 (permalink)  
Old 04-12-2008, 11:24 AM
Member
 
Join Date: Apr 2008
Posts: 15
mark-mlt is on a distinguished road
help
any help pls???
Bookmark Post in Technorati
Reply With Quote
  #5 (permalink)  
Old 04-12-2008, 09:33 PM
Member
 
Join Date: Feb 2008
Location: Oregon, USA
Posts: 24
Bluefox815 is on a distinguished road
Send a message via MSN to Bluefox815
I think you're a little confused, here is an example program for searching a text file named "test_file.txt". This should show you how to use an ActionListener, and a BufferedReader

Code:
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; /* * this program searches for a string in a text file and * says which line it found the string on */ public class SearchText implements ActionListener { private String filename = "test_file.txt"; private JFrame frame; private JTextField searchField; private JButton searchButton; private JLabel lineLabel; private String searchFor; private BufferedReader in; public SearchText() { frame = new JFrame("SearchText"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); searchField = new JTextField(10); searchButton = new JButton("Search"); // this is used later in our actionPerformed method searchButton.setActionCommand("search"); // this sets the action listener for searchButton, which is the current class // because this class implements ActionListener searchButton.addActionListener(this); lineLabel = new JLabel("SearchText"); } public void createGUI() { JPanel topPanel = new JPanel(); topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS)); JPanel bottomPanel = new JPanel(); JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); topPanel.add(searchField); topPanel.add(searchButton); bottomPanel.add(lineLabel); mainPanel.add(topPanel); mainPanel.add(bottomPanel); frame.getContentPane().add(mainPanel); frame.pack(); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { // now we get the action command and if it is search, then it is the button if ("search".equals(e.getActionCommand())) { searchFor = searchField.getText(); searchTheText(); } } private void searchTheText() { // I initialize the buffered reader here so that every time the user searches // then the reader will start at the beginning, instead of where it left off last time try { in = new BufferedReader(new FileReader(new File(filename))); } catch (IOException e) { } String lineContent = null; int currentLine = 0; // this will be set to true if the string was found boolean foundString = false; while (true) { currentLine++; // get a line of text from the file try { lineContent = in.readLine(); } catch (IOException e) { break; } // checks to see if the file ended (in.readLine() returns null if the end is reached) if (lineContent == null) { break; } if (lineContent.indexOf(searchFor) == -1) { continue; } else { lineLabel.setText(String.valueOf(currentLine)); foundString = true; break; } } if (!foundString) lineLabel.setText("Could not find string"); try { in.close(); } catch (IOException ioe) { } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new SearchText().createGUI(); } }); } }

Last edited by Bluefox815 : 04-12-2008 at 10:15 PM.
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
how to search xml file data based on the given keyword from html form? nicemothi XML 0 04-04-2008 11:36 AM
How to read a text file from a Java Archive File Java Tip Java Tips 0 02-08-2008 11:13 AM
Converting text file(.txt) to JPG file(.jpg) in java javadeveloper Advanced Java 0 11-09-2007 06:22 PM
count character in text file as input file aNNuur New To Java 0 06-18-2007 08:46 AM
File Upload - Single to allow the search of .txt files Daniel Advanced Java 1 06-06-2007 06:20 AM


All times are GMT +3. The time now is 12:58 PM.


VBulletin, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2007, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org