fork(3) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main(String[] args) {
  11. ReadFileLast rf = new ReadFileLast();
  12. File file = new File("/Users/nikhil.agrawal/repo/dropwizard-getting-started/src/main/java/com/javaeeeee/dwstart/ReadingLastNLinesfromLogFile/file.txt");
  13. // calling method
  14. rf.readFromLast(file);
  15. //rf.reverseLines(file);
  16.  
  17. }
  18.  
  19. // Read last line of the file
  20. public void readFromLast(File file){
  21.  
  22. int lines = 0;
  23. StringBuilder builder = new StringBuilder();
  24. RandomAccessFile randomAccessFile = null;
  25. try {
  26. randomAccessFile = new RandomAccessFile(file, "r");
  27. long fileLength = file.length() - 1;
  28. // Set the pointer at the last of the file
  29. randomAccessFile.seek(fileLength);
  30. for(long pointer = fileLength; pointer >= 0; pointer--){
  31. randomAccessFile.seek(pointer);
  32. char c;
  33. // read from the last one char at the time
  34. c = (char)randomAccessFile.read();
  35. // break when end of the line
  36. if(c == '\n'){
  37. break;
  38. }
  39. builder.append(c);
  40. }
  41. // Since line is read from the last so it
  42. // is in reverse so use reverse method to make it right
  43. builder.reverse();
  44. System.out.println("Line - " + builder.toString());
  45. } catch (FileNotFoundException e) {
  46. // TODO Auto-generated catch block
  47. e.printStackTrace();
  48. }
  49. catch (IOException e) {
  50. // TODO Auto-generated catch block
  51. e.printStackTrace();
  52. }finally{
  53. if(randomAccessFile != null){
  54. try {
  55. randomAccessFile.close();
  56. } catch (IOException e) {
  57. // TODO Auto-generated catch block
  58. e.printStackTrace();
  59. }
  60. }
  61. }
  62. }
  63. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:11: error: cannot find symbol
        ReadFileLast rf = new ReadFileLast();
        ^
  symbol:   class ReadFileLast
  location: class Ideone
Main.java:11: error: cannot find symbol
        ReadFileLast rf = new ReadFileLast();
                              ^
  symbol:   class ReadFileLast
  location: class Ideone
2 errors
stdout
Standard output is empty