java - How to sort descending contents from file and get it only 5 line -
how read file 5 line , line in sort descending. example have file my.log following contents:
one 2 3 4 5 6 7 8 9 ten eleven twelve
and want result follows:
twelve eleven ten 9 8
my code :
import android.os.bundle; import android.app.activity; import android.util.log; import java.io.bufferedreader; import java.io.filereader; import java.io.ioexception; public class mainactivity extends activity { long sleeptime = 1000; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); string log = "/sdcard/my.log"; try { tail(log); } catch (ioexception e) { e.printstacktrace(); } } public void tail(string filename) throws ioexception { file checkfile = new file(filename); if (checkfile.exists()) { bufferedreader input = new bufferedreader(new filereader(filename)); string currentline = null; while (true) { if ((currentline = input.readline()) != null) { log.d("mylog", currentline); continue; } try { thread.sleep(sleeptime); } catch (interruptedexception e) { thread.currentthread().interrupt(); break; } } input.close(); } else { log.d("mylog", "file not found..."); } } }
but time result content in file in print , result not sort descending. result below:
one 2 3 4 5 6 7 8 9 ten eleven twelve
thanks.
read file line line keep last 5 lines, use linkedlist
, add last read line atthe beginning. if after each line list has more 5 lines delete 5th one:
bufferedreader reader = new bufferedreader(new filereader(mylog)); string line; while((line = reader.readline()) != null) { lastlines.add(0, line); if(lastlines.size() > 5) lastlines.remove(5); } // lastlines have 5 lines in reversed order system.out.println(lastlines);
Comments
Post a Comment