What is the best-practice way to truncate a file in Java? For example this dummy function, just as an example to clarify the intent:
void readAndTruncate(File f, List<String> lines) throws FileNotFoundException { for (Scanner s = new Scanner(f); s.hasNextLine(); lines.add(s.nextLine())) {} // truncate f here! how? }
The file can not be deleted since the file is acting as a place holder.
The flush() method of the FileWriter class flushes the contents of the file. You can use this method to truncate a file.
In Java programming, truncation means to trim some digits of a float or double-type number or some characters of a string from the right. We can also truncate the decimal portion completely that makes it an integer. Remember that after truncation, the number will not be round to its nearest value.
In databases and computer networking data truncation occurs when data or a data stream (such as a file) is stored in a location too short to hold its entire length.
In some situations, you might want to truncate (empty) an existing file to a zero-length. In simple words, truncating a file means removing the file contents without deleting the file. Truncating a file is much faster and easier than deleting the file , recreating it, and setting the correct permissions and ownership .
Use FileChannel.truncate:
try (FileChannel outChan = new FileOutputStream(f, true).getChannel()) { outChan.truncate(newSize); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With