You can do this by opening the file for writing and then trimming its contents , the following example uses NIO:
import static java.nio.file.StandardOpenOption.*; Path file = ...; OutputStream out = null; try { out = new BufferedOutputStream(file.newOutputStream(TRUNCATE_EXISTING)); } catch (IOException x) { System.err.println(x); } finally { if (out != null) { out.flush(); out.close(); } }
Another way : trim only the last 20 bytes of the file:
import java.io.RandomAccessFile; RandomAccessFile file = null; try { file = new RandomAccessFile ("filename.ext","rw"); // truncate 20 last bytes of filename.ext file.setLength(file.length()-20); } catch (IOException x) { System.err.println(x); } finally { if (file != null) file.close(); }
Vlad Gudim
source share