-1

How do I search for a specific entry in a text file that I append to?

I made a GUI to input the data in to, however I can read the whole file, but that is of no use to me as I am thinking from a Users perspective that if an earlier booking wants to be called on I am clueless on the understanding on how to do so. When I read the data back I am trying to instantiate an object.

Here some of my code:

search.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            String booking;
            String where;
            booking = JOptionPane.showInputDialog(" Booking Reference: ");    
            System.out.println("Booking Reference " + e.getActionCommand());
            if (booking.equals("Wales"))
            try{

            FileInputStream fstream = new FileInputStream("Wales.txt");
            // Use DataInputStream to read binary NOT text.
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine;

            while ((strLine = br.readLine()) != null)   {

            System.out.println (strLine);
           }

            in.close();
            }
            catch (Exception ex)
            {
            System.err.println("Error: " + ex.getMessage());
            }
            else if (booking.equals("Scotland"))
            try{

            FileInputStream fstream = new FileInputStream("Scotland.txt");

            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine; 
            while ((strLine = br.readLine()) != null)   {

            System.out.println (strLine);
           }
            where = JOptionPane.showInputDialog("Which booking reference do you wish to search?: ");

            }
            catch (Exception ex)
            {
            System.err.println("Error: " + ex.getMessage());
            }
        }
    });
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130

1 Answers1

1

I think you're going to be better off exploring a file format such as XML, JSON or INI for handling this kind of thing. As you are starting to realize, a text file without a backing format is just that: a text file.

If you just want to read back some Key/Value pairs, try something like an INI file, using this Java INI library.

If you want to instantiate an object from a saved file, XML is a better choice. Saving an object to a text file, and reconstituting that object from the saved file is called Serialization.

Community
  • 1
  • 1
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501