This discussion is archived
12 Replies Latest reply: Apr 27, 2007 11:24 AM by 807606 RSS

Reading files for a specific line

807606 Newbie
Currently Being Moderated
So first things: let's say I have a file called calendar.txt. This is what it currently contains:
042607,I have to go to work today.
The first part is the date and the second part is my entry separated by a comma. When I click a button, I want it to search for a specific line. In this case, the user entered in the date 04/26/07 so upon clicking the button, I would like it to read a text file a search for the line starting with 042607. If it finds a line starting with that date, I want it to read the line and I'll split the line where the comma is and extract my entry that way into a variable such as entry[1].

How do I go about searching for a specific line?
  • 1. Re: Reading files for a specific line
    DrClap Expert
    Currently Being Moderated
    Open the file.

    Read the first line.

    If it's the line you are looking for, stop.

    Otherwise read the next line.

    If it's the line you are looking for, stop.

    Repeat until you reach the end of the file.
  • 2. Re: Reading files for a specific line
    807606 Newbie
    Currently Being Moderated
    Alright. I have it so it'll open the file and read the first line. It takes the line (strLine) and splits it where the comma is ( line = strLine.split(",") ) and if line[0] equals the value of date that we are searching for, it'll set entry (my JTextArea) value as line[1].

    Problem is whenever I search for a specific date, nothing is showing up in my text area.
    public void actionPerformed(ActionEvent ev) {
                    try{
                        String date = month.getText();
                        date += day.getText();
                        date += year.getText();
                        
                        FileInputStream fstream = new FileInputStream("/home/tristan/Desktop/Java Stuff/CalendarProgram/calendar.txt");
                        // Get the object of DataInputStream
                        DataInputStream in = new DataInputStream(fstream);
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        String strLine;
                        //Read File Line By Line
                        while ((strLine = br.readLine()) != null)   {
                            String[] line = strLine.split(",");
                            if (line[0] == date)
                            {
                                entry.setText(line[1]);
                            }
                        }
                        //Close the input stream
                        in.close();
                    }catch (Exception e){//Catch exception if any
                        System.err.println("Error: " + e.getMessage());
                    }
                }
  • 3. Re: Reading files for a specific line
    DrClap Expert
    Currently Being Moderated
    if (line[0] == date)
    Everybody does that wrong once, it seems. This is one of the commonest replies here: Don't use == to see if two Strings contain the same data. Use the equals() method instead:
    if (line[0].equals(date))
  • 4. Re: Reading files for a specific line
    807606 Newbie
    Currently Being Moderated
    Hmm. Well that worked. Does == only not work for strings then?
  • 5. Re: Reading files for a specific line
    807606 Newbie
    Currently Being Moderated
    Hmm. Well that worked. Does == only not work for strings then?
    Quite the opposite. For object references you should almost always use equals(), when it is different from ==.
  • 6. Re: Reading files for a specific line
    807606 Newbie
    Currently Being Moderated
    My last question is, for writing to the file as a new line, that was simple enough. Now I have it so I can write new entries to the file and get entries from the file. Let's say for example we get the entry for 04/27/07 and the entry is This is tomorrow.. Assuming the user would like to update that entry, with the program currently it'd save it to the end of the file leaving me with the original 04/27/07 entry and the new 04/27/07 entry at the end of the file. This is what I currently have for saving the file:
    public void actionPerformed(ActionEvent ev) {
                    try {
                        String date = month.getText();
                        date += day.getText();
                        date += year.getText();
                        
                        String value = entry.getText();
                        
                        String file = "/home/tristan/Desktop/Java Stuff/CalendarProgram/calendar.txt";
                        FileWriter fileOut = new FileWriter(file, true); //The true should mean that it will append
                        BufferedWriter out = new BufferedWriter(fileOut);
                        
                        out.write(date + "," + value);
                        out.newLine();
                        
                        out.close();
                        
                    } catch (Exception e) {
                        System.out.println("Couldnt save file");
                    }
                }
    How would I go about either over-writing the existing line or removing the existing line and writing the new line at the end of the file? Would I be better off to specify a line number to remove rather than searching for a string and to remove its line?
  • 7. Re: Reading files for a specific line
    DrClap Expert
    Currently Being Moderated
    Well, frankly, you would be better off not storing your data in a file if you want to update it like that. A database table would be much easier to deal with.
  • 8. Re: Reading files for a specific line
    807606 Newbie
    Currently Being Moderated
    I do agree that a database would be a much better solution, but this is just a basic file I/O assignment for school.
  • 9. Re: Reading files for a specific line
    DrClap Expert
    Currently Being Moderated
    Okay. People always seem to have the most trouble with school assignments that are teaching them to do things that are a bad idea, as far as I can see. But they are what they are.

    To delete a line from the file, probably the easiest way is to read all the lines from the file one at a time. Write the lines you want to keep to a new file, and the one you don't want to keep, just skip over that. Then close all your files, delete the old file, and rename the new file to be whatever the old file was.

    To add a line to a file... I see you have that taken care of already.
  • 10. Re: Reading files for a specific line
    807606 Newbie
    Currently Being Moderated
    This is what I have right now for saving/updating an entry:
                    try {
                        // Add variables
                        String strLine;
                        
                        // Get the field values
                        String date = month.getText();
                        date += day.getText();
                        date += year.getText();
                        String value = entry.getText();
                        
                        // Open calendar.txt
                        FileInputStream fstream = new FileInputStream("/home/tristan/Desktop/Java Stuff/CalendarProgram/calendar.txt");
                        DataInputStream in = new DataInputStream(fstream);
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        
                        // Make the temp file if it doesn't already exist
                        File temp = new File("/home/tristan/Desktop/Java Stuff/CalendarProgram/calendar.tmp");
                        FileWriter fileOut = new FileWriter(temp, true);
                        BufferedWriter out = new BufferedWriter(fileOut);
                        
                        // Read the input line by line
                        while ((strLine = br.readLine()) != null)   {
                            // Separate the line into an array where the comma exists
                            String[] line = strLine.split(",");
                            
                            // If a calendar entry date already exists, don't write it to the temp file (delete it)
                            if (line[0].equals(date)){
                                out.write("");
                            } else {
                                // Write the read line to the temp file
                                out.write(date + "," + value);
                                out.newLine();
                            }
                        }
                        out.close();
                        //Close the input stream
                        in.close();
                    } catch (Exception e) {
                        System.out.println("Couldnt save file");
                    }
    Right now all it seems to be doing is reading from calendar.txt, outputting to calendar.tmp, but it isn't outputting existing lines from calendar.txt and it's writing my new entry 3 times to the calendar.tmp file.
  • 11. Re: Reading files for a specific line
    DrClap Expert
    Currently Being Moderated
    but it isn't outputting
    existing lines from calendar.txt and it's
    writing my new entry 3 times to the
    calendar.tmp file.
    That's a very good problem description you have there. So it should be easy to look at the code that is writing to the tmp file and see what's up. What exactly is it writing? Why is that the new entry and not the data from the existing entry? Give it a try.
  • 12. Re: Reading files for a specific line
    807606 Newbie
    Currently Being Moderated
    Hah. I got it. So what it was doing was reading every line in the existing file, and if the existing line didn't match my new entry, instead of re-writing the just that was just read into the temp file, it was writing my new entry into the temp file, and since there were 3 existing lines in the TXT file, it wrote my new entry 3 times. I got it working now, including the deleting of the old file and renating the TMP file to TXT.
                    try {
                        // Add variables
                        String strLine;
                        
                        // Get the field values
                        String date = month.getText();
                        date += day.getText();
                        date += year.getText();
                        String value = entry.getText();
                        
                        // Open calendar.txt
                        File txtFile = new File("/home/tristan/Desktop/Java Stuff/CalendarProgram/calendar.txt");
                        FileInputStream fstream = new FileInputStream(txtFile);
                        DataInputStream in = new DataInputStream(fstream);
                        BufferedReader br = new BufferedReader(new InputStreamReader(in));
                        
                        // Make the temp file if it doesn't already exist
                        File temp = new File("/home/tristan/Desktop/Java Stuff/CalendarProgram/calendar.tmp");
                        FileWriter fileOut = new FileWriter(temp, true);
                        BufferedWriter out = new BufferedWriter(fileOut);
                        
                        // Read the input line by line
                        while ((strLine = br.readLine()) != null)   {
                            // Separate the line into an array where the comma exists
                            String[] line = strLine.split(",");
                            
                            // If a calendar entry date already exists, don't write it to the temp file (delete it)
                            if (line[0].equals(date)){
                                out.write("");
                            } else {
                                // Write the existing entries to the temp file
                                out.write(strLine);
                                out.newLine();
                            }
                        }
                        // Wring the new entry / updated entry to the temp file
                        out.write(date + "," + value);
                        out.newLine();
                        out.close();
                        in.close();
                        
                        // Delete the TXT file and rename the TMP file to TXT
                        txtFile.delete();
                        temp.renameTo(new File("/home/tristan/Desktop/Java Stuff/CalendarProgram/calendar.txt"));
                    }
    Thanks for the help! Sometimes you just need to step away from the screen for a while.