I have a .txt file, which I want to process in Java. I want to delete its last line.
I need ideas on how to achieve this without having to copy the enti
By taking RandomAccessFile you can:
Code would be something like this:
LinkedList lines=null;
int howMuch = 1; // one line to read and delete
try{
RandomAccessFile raf = new RandomAccessFile(inputFileName, "rw");
System.out.println("File Length="+raf.length());
long step = 20; // here I advice to write average length of line
long jump = raf.length()();
LinkedList pos = new LinkedList();
Entry,LinkedList> rLinesRead = getRemainingLines(raf,
new AbstractMap.SimpleEntry,LinkedList> (lines,pos));
while(rLinesRead.getKey().size(),LinkedList> getRemainingLines(RandomAccessFile raf,
Entry,LinkedList> linesAlreadyLoadedFromEnd) throws IOException{
LinkedList pLines = linesAlreadyLoadedFromEnd.getKey();
LinkedList pPos = linesAlreadyLoadedFromEnd.getValue();
long init=raf.getFilePointer();
String str = raf.readLine();
if(pPos.size()>0?pPos.getFirst()==0:false || str==null)
return linesAlreadyLoadedFromEnd;
LinkedList lines = new LinkedList();
LinkedList pos = new LinkedList();
if(init==0L ){
lines.add(str);
pos.add(0L);
}
Long tmpPos = raf.getFilePointer();
while ((str = raf.readLine())!=null && !pPos.contains(tmpPos)){
lines.add(str);
pos.add(tmpPos);
tmpPos = raf.getFilePointer();
}
pLines.addAll(0,lines);
pPos.addAll(0,pos);
return new AbstractMap.SimpleEntry,LinkedList> (pLines,pPos);
}