Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File truncate operation in Java

Tags:

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.

like image 910
hyde Avatar asked Jan 11 '13 14:01

hyde


People also ask

How do you truncate a file in Java?

The flush() method of the FileWriter class flushes the contents of the file. You can use this method to truncate a file.

How does truncate work in Java?

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.

What is file truncation?

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.

Can we truncate a file?

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 .


1 Answers

Use FileChannel.truncate:

try (FileChannel outChan = new FileOutputStream(f, true).getChannel()) {   outChan.truncate(newSize); } 
like image 154
Moritz Petersen Avatar answered Oct 14 '22 10:10

Moritz Petersen