Results 1 to 7 of 7
  1. #1
    mark-mlt is offline Member
    Join Date
    Apr 2008
    Posts
    15
    Rep Power
    0

    Red face 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;
    }

    }

  2. #2
    new_2_java is offline Member
    Join Date
    Feb 2008
    Posts
    60
    Rep Power
    0

    Default

    What's the error that you are getting?

  3. #3
    mark-mlt is offline Member
    Join Date
    Apr 2008
    Posts
    15
    Rep Power
    0

    Default

    ermmm no errors... my problem is at the event handler i think ...

  4. #4
    mark-mlt is offline Member
    Join Date
    Apr 2008
    Posts
    15
    Rep Power
    0

    Default help

    any help pls??? :confused::confused::confused:

  5. #5
    Bluefox815 is offline Member
    Join Date
    Feb 2008
    Location
    Oregon, USA
    Posts
    49
    Rep Power
    0

    Default

    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

    Java 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 08:15 PM.

  6. #6
    AbupAnodo is offline Member
    Join Date
    Apr 2009
    Location
    Madagascar
    Posts
    1
    Rep Power
    0

    Default Stupid Question

    Hey everyone... how do I search for more than one word in other posts, so that it returns only posts with those two words?

  7. #7
    dbashby's Avatar
    dbashby is offline Senior Member
    Join Date
    Mar 2009
    Posts
    223
    Rep Power
    6

    Default Searching Text File

    here is my working code for searching a text file, hope this helps

    Java Code:
      String tempMbrship="";
            String tempJdate = "";
            Double tempBmiR;
            tempBmiR = Double.parseDouble("0");
            boolean endofFile = false;
    		boolean openOk = true;
    		boolean search = false;
    
    
       MshipRecord record;
    
       try{
           input= new ObjectInputStream(new FileInputStream(file)); //open file to read
       }
       catch (IOException e){ //trap open error
           optPane1.showMessageDialog(this,"Error in File","Error",optPane1.ERROR_MESSAGE);
           openOk = false;}
    
       if (openOk == true) { //if opened OK
           while ((endofFile == false) && (search== false)) { //if not eof or not found match
               try{
                   record = (MshipRecord)input.readObject();//read record
                   tempMbrship = record.getMbrship();//move record fields into temp storage
                   tempJdate = record.getRdate();
                   tempBmiR = record.getBmindex();
               }
            catch (EOFException e){
                   endofFile = true; //trap EOF
                   optPane1.showMessageDialog(this, "MEMBER NOT FOUND","Error",optPane1.ERROR_MESSAGE);
                   txtMembership.setText("");
                   txtJdate.setText(""); //display blank fields
                   txtBmi.setText("");
            }
               catch (ClassNotFoundException e){ //trap record class
               optPane1.showMessageDialog(this, "Error in File","Error", optPane1.ERROR_MESSAGE);
                       }
               catch (IOException e){ //trap record class error
                   optPane1.showMessageDialog(this,"Error in File","Error", optPane1.ERROR_MESSAGE);
                   }
               if(tempMbrship.equals(txtMembership.getText())){ //is this a match?  *****criteria u search on*****
                   txtMembership.setText(tempMbrship);//display stored fields
                   txtJdate.setText(tempJdate);
    			   txtBmi.setText(Double.toString(tempBmiR));
                   search = true;
               }//end of IF match
               } //end of eof, search loop
               }//end of openOK loop
        }

Similar Threads

  1. count character in text file as input file
    By aNNuur in forum New To Java
    Replies: 7
    Last Post: 03-25-2010, 04:01 PM
  2. Replies: 0
    Last Post: 04-04-2008, 09:36 AM
  3. How to read a text file from a Java Archive File
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-08-2008, 09:13 AM
  4. Converting text file(.txt) to JPG file(.jpg) in java
    By javadeveloper in forum Advanced Java
    Replies: 0
    Last Post: 11-09-2007, 04:22 PM
  5. Replies: 1
    Last Post: 06-06-2007, 04:20 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •