Page 2 of 2 FirstFirst 12
Results 21 to 23 of 23
  1. #21
    davoje is offline Member
    Join Date
    Nov 2009
    Posts
    1
    Rep Power
    0

    Default Another option?

    I was searching for this topic and found this thread. However, I couldn't find any easy way to do this without reading the whole file so I rolled my own.

    What's wrong with this solution?

    It seems to be both quick and easy to implement using a combination of seeking to near the end and then using readline in the same way as the other solution at the beginning of the thread.

    The only downside I can see is that you have to know the max line length which seems reasonably for the majority of files (including logs).

    Java Code:
        
    public static String lastLine (String fileName) {
        	String last = "";
        	long maxLineLength = 200;
        	
        	try {
        		RandomAccessFile raf = new RandomAccessFile(fileName, "r");
        		long len;
    			try {
    				len = raf.length();
    				if( len > maxLineLength ) {
    					raf.seek(len - maxLineLength);
    				}
    				String s = "";
    				while( (s = raf.readLine()) != null) {
    					last = s;
    				}
    			} catch (IOException e) { 
    				Log.e(LOG_TAG, e.toString());
    			}    		    		
        	} catch (FileNotFoundException e) {
        		Log.e(LOG_TAG, e.toString());
        	}    	
        	return last;
    }
    Thanks
    davo

  2. #22
    sterf is offline Member
    Join Date
    Apr 2012
    Posts
    6
    Rep Power
    0

    Default Re: Another option?

    You do not need to know the length.
    Here is my superfast and stable code.
    Lemme know what you think of it.

    explanation:
    main method calls test2 -> get some big file -> run lastline( file)
    that is a simple wrapper around stuff you do not want to bother with, like exceptions and crap.
    -> this runs _lastline() which is a private method that jumps to the last position.

    The line "is the last line", one position before it you find the "previous line".

    All this took about two hours to code, and you could test it on fifty times the integral version of the Bible.
    Amen ;-)


    public static void test2() {
    //String loc = "C:\\dev\\Java\\eclipse\\workspace\\jsoup\\data\\t est-large-text.txt"; //0ms
    String loc = "./data/test/largefiles/html40.txt"; //1ms for 1KB
    File f = new File( loc );
    long start = System.currentTimeMillis();

    String lastline = lastLine(loc);
    System.out.println(lastline);
    long delta = System.currentTimeMillis()-start;
    System.out.println("took " + delta+ "ms");
    }

    /**
    * simple test.
    * @param args
    */
    public static void main(String[] args) {
    //test1();
    test2();

    }


    /**
    * Optimized last line of file reader.
    * @param fileName
    * @return return the last line, possibly only "\n",
    * or null if the file was not found
    * @throws IOException
    * @author Kos
    * @version 1.0 initial. Useful for big files also.
    */
    public static String lastLine (String fileName) {

    RandomAccessFile raf;
    try {
    raf = new RandomAccessFile(fileName, "r");
    } catch (FileNotFoundException e) {
    logger.warn("file '"+fileName+"' not found, please check your client code and try again..."
    + "\r\n"+ e.getLocalizedMessage() );
    return null;
    }

    long len;
    try {
    len = raf.length();
    } catch (IOException e) {
    logger.warn("file '"+fileName+"'.length() problem, please check your client code and try again..."
    + "\r\n"+ e.getLocalizedMessage() );
    return null;
    }
    //{post: raf exists and len is its length}

    try {
    return _lastLine(raf,len, fileName); //the real meat
    } catch (IOException e) {
    return null; //info already provided by the private.
    }
    }


    /**
    * private method, for separating exceptions.
    * @param raf: proper pointer to proper file, as provided by the calling method.
    * @param fileName: for logging purposes only
    * @return
    * @throws IOException
    */
    private static String _lastLine (RandomAccessFile raf, long len, String fileName) throws IOException {

    //1. guess the last line. assume about 1 character per line ("\r\n" is two characters)
    long eol = len;
    String tempLine;
    do{
    raf.seek(eol++);
    tempLine = raf.readLine(); //test
    } while( (tempLine = raf.readLine()) != null);
    //post: tempLine == null, eol is too much.

    //now simply go back. Decide that you lost the last line,
    // if this line != next line.
    raf.seek(--eol);
    String lastline;
    String nextline=null;
    do{
    lastline = nextline;
    raf.seek(--eol);
    nextline= raf.readLine(); //test
    if(lastline!=null && nextline!=null){
    if(lastline.length()>0 && nextline.length()<= lastline.length() ){
    return lastline;
    }
    }
    } while( eol>0);

    raf.seek(0);
    return raf.readLine();
    }

  3. #23
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,455
    Rep Power
    20

    Default Re: [SOLVED] read last line

    Don't wake up old dead threads.
    Do read the forum FAQ and learn how to format code on a forum.

    db

    THREAD CLOSED
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Page 2 of 2 FirstFirst 12

Similar Threads

  1. how to read a form with JFS
    By crispy in forum JavaServer Faces (JSF)
    Replies: 2
    Last Post: 05-01-2008, 04:07 PM
  2. Read file
    By tajinvillage in forum Threads and Synchronization
    Replies: 0
    Last Post: 01-29-2008, 10:10 AM
  3. How to read the following
    By rrp in forum New To Java
    Replies: 0
    Last Post: 12-03-2007, 07:16 PM
  4. Reading in data from file line by line
    By bluekswing in forum New To Java
    Replies: 1
    Last Post: 10-02-2007, 01:19 AM
  5. read txt file
    By sureshsri1981 in forum JavaServer Pages (JSP) and JSTL
    Replies: 0
    Last Post: 08-05-2007, 04:49 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
  •