9 Replies - 1163 Views - Last Post: 16 May 2011 - 02:45 AM Rate Topic: -----

#1 dansaDisco   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 15-May 11

Finding a string in txt file

Posted 15 May 2011 - 10:50 AM

Hey guys. I'm currently doing a e-book course in basic Java, but I've run into a problem.

I've done all the assignments so far, but I really can't get this to work no matter how much i re-read the chapter about reading from files.

What I'm asked to do is this (translated from swedish):
"Create an application that lets the user write in a name in a JTextField,
after the input, make the program search through a .txt file for the name, then print a result message in a JLabel."

I do understand how to write a swing application with basic GUI and such, and I know how to read from a file.
But the book never told me about finding a specified string from a file.

And sorry, the var's are all in swedish, but I hope you can understand what I've done.

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

public class Readlist extends JFrame {

    private JLabel instruktion;
    private JTextField namnruta;
    private JLabel resultat;
    private JButton sok;
    private String namn;
    private String file = "namnlista.txt";

    class Lyssnare implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource() == namnruta) {
                String data = namnruta.getText();
                namn = data;
            } else {
                try {
                    boolean hittad = false;
                    FileReader fr = new FileReader(file);
                    BufferedReader bf = new BufferedReader(fr);
                    String line = bf.readLine();
                   
                   // Here is where I need help!

                    }

                    bf.close();
                    if (!hittad) {
                        resultat.setText(namn + " hittades inte.");
                    }
                } catch (IOException ex) {
                }
            }
        }
    }

    public Readlist() {
        super("Sök efter namn");

        JPanel p = new JPanel();
        p.setBackground(Color.white); 
        setContentPane(p);

        instruktion = new JLabel("Sök efter namn i namnlista.txt"); 
        namnruta = new JTextField(15); 
        sok = new JButton("Sök"); 
        resultat = new JLabel(""); 

        p.add(instruktion);
        p.add(namnruta);
        p.add(sok);
        p.add(resultat);


        Lyssnare minLyssnare = new Lyssnare();
        sok.addActionListener(minLyssnare);
    }
}



Hopefully I can get some help in this :)

edit: YES, I've searched, but unfortunately I couldn't understand any of the responses given in other topics :(

This post has been edited by dansaDisco: 15 May 2011 - 10:53 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Finding a string in txt file

#2 japanir   User is offline

  • jaVanir
  • member icon

Reputation: 1014
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Finding a string in txt file

Posted 15 May 2011 - 10:56 AM

Read the file line by line.
for each line, use index of to check if the name String is in that line. like:
while((line = bf.readLine()) != null){
  if(line.indexOf(name) != -1){
    //found the name string
  }
}

Was This Post Helpful? 1
  • +
  • -

#3 dansaDisco   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 15-May 11

Re: Finding a string in txt file

Posted 15 May 2011 - 11:27 AM

Tried to implement that, but when I use the search button, I get a whole lot of errors..


The Action Listener class right now:
    class Lyssnare implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource() == namnruta) { 
                String namn = namnruta.getText();
            } else {
                try {
                    FileReader fr = new FileReader(fil);
                    BufferedReader bf = new BufferedReader(fr);
                    String line = bf.readLine();

                    while ((line = bf.readLine()) != null) {
                        if (line.indexOf(namn) != -1) {
                            resultat.setText(namn + " hittades!");
                        }
                    }
                    bf.close();
                } catch (IOException ex) {
                }
            }
        }
    }


The errors I get:

Quote

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.lang.String.indexOf(String.java:1733)
at java.lang.String.indexOf(String.java:1715)
at uppgift61.Readlist$Lyssnare.actionPerformed(Readlist.java:30)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6374)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6139)
at java.awt.Container.processEvent(Container.java:2085)
at java.awt.Component.dispatchEventImpl(Component.java:4736)
at java.awt.Container.dispatchEventImpl(Container.java:2143)
at java.awt.Component.dispatchEvent(Component.java:4566)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4621)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4282)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4212)
at java.awt.Container.dispatchEventImpl(Container.java:2129)
at java.awt.window.dispatchEventImpl(window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4566)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:680)
at java.awt.EventQueue.access$000(EventQueue.java:86)
at java.awt.EventQueue$1.run(EventQueue.java:639)
at java.awt.EventQueue$1.run(EventQueue.java:637)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:653)
at java.awt.EventQueue$2.run(EventQueue.java:651)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:650)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Was This Post Helpful? 0
  • +
  • -

#4 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3744
  • View blog
  • Posts: 17,121
  • Joined: 20-September 08

Re: Finding a string in txt file

Posted 15 May 2011 - 01:48 PM

Change that to

        String line = null;

        while ((line = bf.readLine()) != null) {
            if (line.indexOf(namn) != -1) {
                resultat.setText(namn + " hittades!");
            }
        }


Was This Post Helpful? 1
  • +
  • -

#5 dansaDisco   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 15-May 11

Re: Finding a string in txt file

Posted 16 May 2011 - 01:04 AM

Apparently there was something wrong with the file It was supposed to read from, So I made the main method write a new file for me, and now it works just fine.

Though while trying to solve my problem I did some heavy re-reading and noticed that I've used SpringTokenizer for this thing before, so I changed everything >_< But yeah, big up for your help anyway.

Final code for reference:

Uppgift61.java:
package uppgift61;

import java.io.*;

public class Uppgift61 {

    public static void main(String[] args) throws IOException {
        String skrivfil = "test.txt";
        FileWriter fw = new FileWriter(skrivfil);
        BufferedWriter bw = new BufferedWriter (fw);
        PrintWriter ut = new PrintWriter(bw);
        ut.println("anna");
        ut.println("lisa");
        ut.println("kalle");
        
        ut.close();
        
        Readlist fonster = new Readlist();
        fonster.setVisible(true);

    }
}



Readlist.java:
package uppgift61;

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

public class Readlist  extends JFrame  {

    private JLabel instruktion;
    private JTextField namnruta;
    private JLabel resultat;
    private JButton sok;

    class Lyssnare implements ActionListener {

        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource() == namnruta) { 
            } else {
                try {
                    String namn = namnruta.getText();
                    boolean hittad = false;
                    String fil = "test.txt";
                    FileReader fr = new FileReader(fil);
                    BufferedReader bf = new BufferedReader(fr);
                    String line = bf.readLine();
                    while (line != null){
                        StringTokenizer tk = new StringTokenizer(line, "\n");
                        String tkNamn = tk.nextToken();
                        if(tkNamn.equals(namn)){
                            resultat.setText("Hittade "+namn);
                            hittad = true;
                        }
                        line = bf.readLine();
                    }
                    bf.close();
                    if(!hittad){
                        resultat.setText("Hittade inte " + namn);
                    }
                }
                catch(FileNotFoundException e1){
                    System.out.println("Hittade inte filen");
                }
                catch (IOException e2) {
                    System.out.println(e2);
                }
            }
        }
    }

    public Readlist() {
        super("Sök efter namn");


        instruktion = new JLabel("Sök efter namn i test.txt");
        namnruta = new JTextField(15); 
        sok = new JButton("Sök"); 
        resultat = new JLabel("Resultat"); 

        // Lägger till våra komponenter i panelen "p"
        JPanel p1 = new JPanel();
        JPanel p2 = new JPanel();
        JPanel p3 = new JPanel();
        p1.setLayout(new GridLayout(3, 1));
        getContentPane().setSize(200,100);
        getContentPane().add(p1, "North");
        getContentPane().add(p2, "Center");
        getContentPane().add(p3, "South");
        p1.add(instruktion);
        p2.add(namnruta);
        p2.add(sok);
        p3.add(resultat);

        Lyssnare minLyssnare = new Lyssnare();
        sok.addActionListener(minLyssnare);
    }
}


This post has been edited by dansaDisco: 16 May 2011 - 01:05 AM

Was This Post Helpful? 0
  • +
  • -

#6 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3744
  • View blog
  • Posts: 17,121
  • Joined: 20-September 08

Re: Finding a string in txt file

Posted 16 May 2011 - 02:03 AM

StringTokenizer is a legacy class and should be avoided in favour of String.split unless you have a special reason for not doing so
Was This Post Helpful? 0
  • +
  • -

#7 dansaDisco   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 15-May 11

Re: Finding a string in txt file

Posted 16 May 2011 - 02:16 AM

Hm, I see. If I may ask a quick question, not related to this (but not really worth starting a new topic about :P).

I want to check if two JTextFields are NOT empty, I'm using this if statement:
if (inputF.getText() != null && inputT.getText() !=null)


But even if the fields are empty it runs the actions inside.
Any idea?
Was This Post Helpful? 0
  • +
  • -

#8 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3744
  • View blog
  • Posts: 17,121
  • Joined: 20-September 08

Re: Finding a string in txt file

Posted 16 May 2011 - 02:25 AM

The api should have really implemented this in java.lang.String itself, but you can use the following


public static boolean isEmpty(String s) {
    return s == null || (s.trim().length() == 0);
}


It's worth noting that JTextField.getText() never returns a null String, but the above code is a general solution

This post has been edited by g00se: 16 May 2011 - 02:26 AM

Was This Post Helpful? 2
  • +
  • -

#9 dansaDisco   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 15-May 11

Re: Finding a string in txt file

Posted 16 May 2011 - 02:41 AM

Awesome, thanks a lot for that one :)

this will be the if operator?
if (isEmpty(inrutaF.getText()) ==false && isEmpty(inrutaT.getText())== false)

Was This Post Helpful? 0
  • +
  • -

#10 g00se   User is offline

  • D.I.C Lover
  • member icon

Reputation: 3744
  • View blog
  • Posts: 17,121
  • Joined: 20-September 08

Re: Finding a string in txt file

Posted 16 May 2011 - 02:45 AM

Yes, that will work
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1