Open to a better solution. Just a trial
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PrintLastNSentences {
public void printLastNSentences(int n) {
try {
/*creating a simple file */
File file = new File("/home/jasleen/d.txt");
FileWriter fw = new FileWriter(file);
for (int i = 0; i < 100000; i++) {
fw.append("\nAs Macbeth takes a journey, so does his speech and its punctuation. Note the increasingly long sentences as Macbeth delves deeper into the horror and chaos of the contemplated deed. The first complete sentence is nearly five lines. The next sentence is over nine lines. And if, for the purpose of analyzing this speech, we consider the semicolons and colons to serve the same purpose as periods (which they could, depending on the actor), then we see even more clearly the escalation of sentence length. While Macbeth begins with a simple five-word phrase (\"He's here in double trust\") he culminates with a 36-word sentence (ending with \"drown the wind.\").");
}
fw.close();
/*Using a RandomAccessFile to seek the file*/
RandomAccessFile raf = new RandomAccessFile(file, "rw");
/*Retreiving the length of the file and subtracting by
1 to seek to the last character of the file*/
long pointer = file.length() - 1;
/*Using a StringBuilder to store the setence character by character.
Not used String because String is immutable*/
StringBuilder sb = new StringBuilder();
int linecount = 0;
/*Running the loop till we have reached a point where no more characters
are left to read or 10 lines have been processed*/
while (pointer != -1 && linecount < n) {
/*Seeking to the current poistion*/
raf.seek(pointer);
/*Reading the byte*/
int aByte = raf.read();
/*Checking to see if the current character is a new line character*/
if (((char) aByte) != '\n') {
sb.insert(0, (char) aByte); //here we are inserting the char at first position
} else {
if (sb.length() > 1)///This is a check to avoid blank sentences
///It can be removed if blank sentence are also allowed.
{
System.out.println(sb.toString());
sb.delete(0, sb.length()); //This is to empty the string builder
linecount++;
}
}
pointer--;
}
raf.close();//Closing the file after reading
} catch (FileNotFoundException ex) {
Logger.getLogger(PrintLastNSentences.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(PrintLastNSentences.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String args[]) {
new PrintLastNSentences().printLastNSentences(10);
}
}
0 comments:
Post a Comment