Just to add on to stribizhev's answer, you may also want to use System.lineSeparator()
as opposed to \s
(in most cases \s
more useful but i do not know your needs)
Since I'm posting an answer (cant make comments yet), I might as well go out. I was under the impression that you were trying to re-size the file. (and again i just used System.lineSeparator()
to show how to use it.
String regex = "[^"+ System.lineSeparator() + "]" + System.lineSeparator() + "$"; //or use "\\S\\s*$";
Matcher whiteSpace = Pattern.compile(regex).matcher("");
int threshold = 4; //number of characters to look back at the end of file.
byte[] readBytes = new byte[threshold]; //for whatever reason we can't just read in a string :/
try ( RandomAccessFile file = new RandomAccessFile(input_file, "rw")){
//start at the end of file, look for non line separator character.
long cursor;
for(cursor = file.length() - threshold; cursor > 0 ; cursor=cursor-threshold){
file.seek(cursor);
file.readFully(readBytes);
if(whiteSpace.reset(new String(readBytes)).find()){
cursor = cursor + whiteSpace.start() + 1;
break;
}
}
file.setLength(cursor);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
no idea what the performance will be like, but i don't read the whole file in, and start from the end.