Search code examples
javasearchtext-filesjgrasp

Searching for specific text in a text file. Returning it to a textbox


I am very new to java. I am working on project for class that would look up books in a text file and display information about them. Primarily if the book is in stock or not. The text file is set up like this: {ISBN, Author, Type, Stock}

I have coded a user interface that allows the user to type in ISBN, Author, and Type. Ideally, I would like for the user to just search one of these and return the needed information. However, just searching via ISBN would be acceptable for now. My code right now only takes what is typed into the textboxes and displays it in a large textbox. I am somewhat familiar with reading a text file in but have no idea how I would take the text from a textbox and use it to search the file. Any help would be greatly appreciated.

Here is my code:

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.sql.*;


public class InventoryInterface extends JFrame
{
   private static final int FRAME_WIDTH = 600;
   private static final int FRAME_HEIGHT = 350;

   private JButton btnSearch;
   private JButton btnDatabase; 
   private JButton btnRefresh; 
   private JLabel lblISBN, lblAuthor, lblType;
   private JTextField txtISBN, txtAuthor, txtType;
   private JTextArea txtOutput;


   public InventoryInterfaceSimple()
   {
      createComponents();
      setSize(FRAME_WIDTH, FRAME_HEIGHT);
   }

   public void createComponents()
   {

      btnSearch = new JButton("Search");
      lblISBN = new JLabel("ISBN");
      lblAuthor = new JLabel("Author");
      lblType = new JLabel("Type");

      txtISBN = new JTextField(10);
      txtAuthor = new JTextField(10);
      txtType = new JTextField(10);
      txtOutput = new JTextArea(30,30);
      txtOutput.setText("");
      txtOutput.setEditable(false);   
      ActionListener action = new InventoryOutput();
      btnSearch.addActionListener(action);



      JPanel panel = new JPanel();
      panel.setLayout(null);



      lblISBN.setBounds(10,10,50,25);
      txtISBN.setBounds(55,10,125,25);
      lblAuthor.setBounds(10,40,50,25);
      txtAuthor.setBounds(55,40,125,25);
      lblType.setBounds(10,70,50,25);
      txtType.setBounds(55,70,125,25);

      btnSearch.setBounds(30,130,150,25);

      JScrollPane scrollArea = new JScrollPane(txtOutput);
      scrollArea.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
      scrollArea.setBounds(200,10,350,200);
      panel.add(scrollArea);

      panel.add(lblISBN);
      panel.add(txtISBN);
      panel.add(lblAuthor);
      panel.add(txtAuthor);
      panel.add(lblType);
      panel.add(txtType);
      panel.add(btnSearch);
      panel.add(scrollArea);

      add(panel);

   }

   class InventoryOutput implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         String inventoryString = "";
         inventoryString += txtISBN.getText() + " - ";
         inventoryString += "Author: " + txtAuthor.getText() + " - ";
         inventoryString += "Type: " + txtType.getText() + " - ";

         txtOutput.append(inventoryString + "\n");

         txtISBN.setText("");
         txtAuthor.setText("");
         txtType.setText("");


      }
   } 

}
​

Solution

  • you can replace your code with this.. this is a starting point, you can do many improvements to this code, but this will work. change REPOSITORY_FILE_PATH to your data file

       class InventoryOutput implements ActionListener {
        private final String REPOSITORY_FILE_PATH = "C:\\temp\\book-repo.txt";
        private final File REPOSITORY_FILE = new File(REPOSITORY_FILE_PATH);
    
        public void actionPerformed(ActionEvent event) {
            String inventoryString = "";
    
            String requestedISBN = txtISBN.getText().trim().toLowerCase();
            String requestedAuthor = txtAuthor.getText().trim();
            String requestedType = txtType.getText().trim();
    
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(REPOSITORY_FILE));
                String line;
                while ((line = reader.readLine()) != null) {
                    String lineLtrim = line.toLowerCase().replaceAll("^\\{", ""); //{
                    String lineRtrim = lineLtrim.replaceAll("\\}$", ""); //}
                    String[] data = lineRtrim.split(","); //ISBN, Author, Type, Stock
                    if (data.length < 4) {
                        throw new IllegalArgumentException("bad datafile: All fields must be entered: " + line);
                    }
                    if (data[0].equals(requestedISBN)) {
                        inventoryString += txtISBN.getText() + " - Author: " + data[1] + " - Type: " + data[2] + " - Stock:" + data[3];
                        txtOutput.append(inventoryString + "\n");
                        return;
                    }
                }
                reader.close();
                inventoryString += txtISBN.getText() + " -  Not Found";
                txtOutput.append(inventoryString + "\n");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    you can just add this main() code to test, ideally you should write unit test-- to cover all cases.

    public static void main(String[] args) {
        JFrame f = new InventoryInterface();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setPreferredSize(new Dimension(600, 600));
        f.pack();
        f.setVisible(true);
    }
    

    data file

    {ISBN1234,me,drama,5}
    {ISBN1235,me,Tech,0}
    {ISBN1236,me,Fiction,2}
    {ISBN1237,me,Audio/Kids,4}
    

    Not sure which part you did not get,,

    1. on the listener-- we read the ISBN entered by user String requestedISBN = txtISBN.getText().trim().toLowerCase(); and convert it in lower case so, we can compare with lower-cased-data
    2. then we read your data file (line by line)
    3. we then from each line we remove character "{" and "}" // comment says that
    4. then we get "isbn,author, type, stock" , so we split by ","
    5. split gives us array of string putting each element in array in order i.e data[0] has isbn, data[1] has author ...etc
    6. we check if the data file is correct by making sure we have all elements in there i.e if (data.length < 4) {
    7. we throw exception if the size of array is not <4 i.e. we found that the data file has incorrect data.
    8. then we compare if the input isbn (data[0]) is same as one of the line element from your data file
    9. if we find a match we display it in the textArea and exit the loop,
    10. if we dont find we display "not Found"

    If you wrote the code (listener) yourself, this should be trivial to you.