Easiest way to truncate / trim last character in a file

1.4k Views Asked by At

What is the most simple way to delete the last character in a file in Java?

1

There are 1 best solutions below

4
On

You can use FileChannel truncate:

try {
    File file = new File("fileToTruncate");
    FileChannel fileChannel = new FileOutputStream(file, true).getChannel();
    fileChannel.truncate(fileChannel.size() - 1); //Removes last character
    fileChannel.close();
}
catch (FileNotFoundException ex) {

}
catch (IOException ex) {

}