Results 1 to 9 of 9
  1. #1
    Jman85 is offline Member
    Join Date
    Nov 2010
    Posts
    14
    Rep Power
    0

    Default Reverse search a Text file from last line to top line

    Hey,

    I would like to search a text file and start outputting the contents of the txt file from the last line to the first line. For example;

    ABCDE
    FGHIJ

    I want it to be outputted as;
    FGHIJ
    ABCDE

    What I want to accomplish out of this is for a user to search a word and output say the last 4 lines that contain that word from the most recent log entry (I am recording the activity of a chatroom and so I want the most recent of the chatrooms messages.) Unless there is a way of stacking the messages in a chatroom from a user, so the most recent messages are at the top of the text file.

    Thank you.

    EDIT: Also please do not complain that I haven't looked on the internet, I have, all my google searches are filled with purple links, none of them really useful, this code in my opinion should be simple, well hopefully it is.
    Last edited by Jman85; 12-27-2010 at 11:45 AM.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    What I want to accomplish out of this is for a user to search a word and output say the last 4 lines that contain that word from the most recent log entry (I am recording the activity of a chatroom and so I want the most recent of the chatrooms messages.) Unless there is a way of stacking the messages in a chatroom from a user, so the most recent messages are at the top of the text file.

    I think the last sentence provides some insight. A text file is not a good way of logging the messages:
    * It "embeds" information like who posted the message that has then to be recovered by parsing. Even figuring out where one message ends and another begins will require work.
    * it grows and grows - consider looking for a phrase like "hapex legomenon" that might only have been used several years ago if at all. A linear search will scale badly.
    * it is arranged bassawkwardly from oldest to newest

    Consider putting the messages into a database with fields like author and date that can be indexed. That way you can rely on someone else's code to do the hard work of searching and sorting in a way that scales.

    -----------------------

    btw, no-one is likely to complain about lack of searching. but most will suggest it because that's the most helpful thing to suggest. If you can't get a result that's helpful (ie what you find is either inappropriate or unintelligible) say what you have found and why it doesn't suit. This gives everyone a better idea of where you're coming from. (for example I wondered about posting the suggestion of using a database because I would have thought a search would have pointed you in that direction. Perhaps using a database is unsuitable for some reason.)
    Last edited by pbrockway2; 12-27-2010 at 07:05 PM.

  3. #3
    Jman85 is offline Member
    Join Date
    Nov 2010
    Posts
    14
    Rep Power
    0

    Default

    Yeah

    I wasn't planning to to use a Database or anything, and I didn't want to confuse people by putting that "chat loggging" system I have in place to direct you away from what I want to do. I can log the messages, perfectly, everything is fine there, I can search a word in a logged message within the text file and output it perfectly. All I want to do is search the text file backwards. I read somewhere about "stacking" the text file, maybe someone has some knowledge or insight on what I want to do.

    1. If you can store the messages by stacking them ontop of eachother in the text file OR
    2. Search the text file backwards

    The database is a good idea, but not what I want. Please future posters, stick within the subject.

    Edit: Believe me, this text file is not going to fill up with years worth of messages, just weeks or even days worth. Maybe each week I will empty the file. In the end its just a bit of fun and testing out really.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    If you are not worried about memory, speed or the elegance of an object oriented structure to the data...

    For searching a text file for the last occurances of a phrase in its lines:

    * use a buffered reader to read the entire contents of the file line by line into a list of strings (appending each line to index zero).
    * iterate over the list looking for the phrase within the line until you have found as many as required.

    (If using the collections framework to deal with ... the collection of lines isn't fun, you can read the entire file into one big string, split that on newlines, and iterate over the resulting array from end to start.)

    For "stacking", ie building up a text file so that the lines appear in the reverse order to that in which they are added you have to do a little dance with file names to minimise the danger of losing data. Specifically to prepend (==stack) a line to the file:

    * write the line to a temporary file.
    * read the contents of the file and append it to the temporary file.
    * delete the file
    * rename the temporary file with the name of the original file.

    (With some OSs under some circumstances you may have to copy the temporary file to the previous location of the original file and then delete the temporary file. In this case you should ensure there was no I/O error before deleting the temporary file.)

    ----------------------

    Please future posters, stick within the subject.

    Given what some would have the world become it is perhaps quite utopian to expect the season of "peace and goodwill" to retain its statutory 12 days. That being the case, I would invite readers of this thread to put aside feeling jolly as well and heed the somber advice of Hilaire Belloc as regards storing information in flat files made up of little bits of String.
    Last edited by pbrockway2; 12-27-2010 at 08:30 PM.

  5. #5
    user0 is offline Senior Member
    Join Date
    Dec 2010
    Posts
    100
    Rep Power
    0

    Default

    hi - I have never done this before but I would do this one of two ways.
    1. Use a Scanner object to read lines from the file and store them into a data structure such as an ArrayList, which can then be sorted in reverse. Once you have that, you can search the array list for the word you are looking for.
    2. Using InputStream object to read the file backwards. Try reading http://mattfleming.com/node/11

    I'm sure there are many more ways of accomplishing what you require. I hope this helps you get a start.

    Best,
    --user0--

  6. #6
    Jman85 is offline Member
    Join Date
    Nov 2010
    Posts
    14
    Rep Power
    0

    Default

    Hey,

    Quote Originally Posted by pbrockway2 View Post
    * use a buffered reader to read the entire contents of the file line by line into a list of strings (appending each line to index zero).
    * iterate over the list looking for the phrase within the line until you have found as many as required.
    I'm not sure what this means. You want each line with a 0 appended to it ?
    ABCD0
    EFGHI0
    Then you want me to iterate through the whole list and grab each line that has the word I am looking for in it ? How would I be able to get, say the LAST 4 entries in the text file with those phrases in it ? Its slightly confusing.

    User0, I have been to that website and I replaced the text file with the one I have, and it crashed. I have actually seen that website as well.
    EDIT:I ran it, it works, and it gives each line a number, but what does it do ? Im looking at the output and its not sorting them from bottom to top, if thats what it is suppose to do.
    Ok, it gives two outputs, one is "Head write.txt" and it gives each line in the txt file a number, the next one is "Tail of write.txt", and it starts giving a number for each line in the text file, starting from the middle and not at the top, and going down, So...What does this mean ? How is it useful.

    And I have never used ArrayLists, is there a small simple example ?
    Last edited by Jman85; 12-28-2010 at 10:49 AM.

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    I'm not sure what this means. You want each line with a 0 appended to it ?
    No. An instance of List provides two methods for adding things to the list - what I mean is that you could use the one that lets you specify the position (index) in the list.

    If you add a bunch of things at index zero (the first element of the list) they will end up in the list "backwards". Eg consider what happens when the strings "eh", "bee", "sea" are added in that order:

    Java Code:
    index: 0    1    2
    
           eh
           bee  eh
           sea bee eh

    Adding an element at index zero has the effect of pushing the other elements "down".

    In code it would look like (untested):

    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    public class Test {
        public static void main(String[] args) {
            List<String> list = new ArrayList<String>();
            list.add(0, "eh");
            list.add(0, "bee");
            list.add(0, "sea");
                // now print them...
            for(String str :list) {
               System.out.println(str);
            }
        }
    }

    This is an example of using lists - but for more details you should consult a textbook or Oracle's Tutorial section on Collections. As you will probably find there a list can also be reversed using a method in the Collections class.

  8. #8
    Jman85 is offline Member
    Join Date
    Nov 2010
    Posts
    14
    Rep Power
    0

    Default

    Hey pbrockway2,

    I used your method and redesigned it for my program, now on opening a connection to the chatroom, it reads the first 40 lines of the chatroom that were left (not active), and it sorts them so that the newer messages where at the top, and the text file line by line, is all sorted and such. But if someone was to post a newely added message, their message would go all the way to the bottom of the text file, being the 41st message recorded in the log text. So in an active chat room, it doesn't work.

    To make a simpler scene, if a user enters "B" in a Java system.in environment, and it gets stored in a text file. I want whatever the second user enters to be at the top of the text file. Sorry for repeating my self.

    But thanks pbrockway2, I nearly had it.

    EDIT: Actually to be honest, I don't this is actually possible, to keep storing messages at the top of a text file and drop the other entries a line below in an active environment.

    EDIT: If all else fails, Maybe I can take what I am currently doing with the chatroom, and do it with the text file log entries. So when ever a user requests to search an entry, I can take First.txt file and flip all the entries like I did with the chatroom, and then the search can begin in the newely filled Second.txt file. And when the search finishes, the txt file is wiped clean or deleted. I am not sure if you actually stated this already, and maybe I read it wrong pbrockway2, cause I THINK this was your previous idea.

    I have another idea, which is to go all the way down to the bottom of the text file that has a line number next to the log message and if a certain phrase isn't located, to skip again all the other log messages to the second last entry and check if the word is there, but this is probably even slower. I would utilize the "startsWith(number)" feature. And the first loop will count how many log entries I have, and the second loop will decremental update. Confusing but hopefully you get the idea.
    Last edited by Jman85; 12-28-2010 at 02:54 PM.

  9. #9
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default

    But if someone was to post a newely added message, their message would go all the way to the bottom of the text file

    Yes. As I said reading the lines from a file and putting them into a list so they appear last-to-first is one way of searching for the last line in which some string occurs.

    If you want to display the lines in the reverse order to that in which they were added you could implement the other algorithm I suggested: adding lines to a file by prepending them (ie adding them to the start of the file).

Similar Threads

  1. Inserting line into text file
    By Onra in forum Advanced Java
    Replies: 5
    Last Post: 09-14-2010, 12:21 PM
  2. Help! - How to insert a new line to a text file
    By matpj in forum New To Java
    Replies: 13
    Last Post: 02-24-2010, 06:28 PM
  3. Replies: 4
    Last Post: 09-10-2009, 11:18 AM
  4. Replies: 7
    Last Post: 11-19-2008, 03:09 PM
  5. Saving To A New Line Using A Text File
    By jadaleus in forum Advanced Java
    Replies: 10
    Last Post: 10-24-2008, 08:21 PM

Posting Permissions

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