FileChannel Truncate Example
This program demonstrates truncating a file using FileChannel.
Problem Statement
Write a Java program that truncates a file to a specific size using FileChannel.truncate().
Source Code
| 1 | import java.io.*; |
| 2 | import java.nio.channels.*; |
| 3 | import java.nio.file.*; |
| 4 | public class FileChannelTruncateExample { |
| 5 | public static void main(String[] args) throws Exception { |
| 6 | System.out.println("Eduinq FileChannel Truncate Example"); |
| 7 | FileChannel channel=FileChannel.open(Paths.get("truncate.txt"),StandardOpenOption.WRITE,StandardOpenOption.CREATE); |
| 8 | channel.write(java.nio.ByteBuffer.wrap("Eduinq Truncate Example Data".getBytes())); |
| 9 | channel.truncate(10); |
| 10 | channel.close(); |
| 11 | System.out.println("Eduinq File Truncated Successfully"); |
| 12 | } |
| 13 | } |
Program Output
Eduinq FileChannel Truncate Example Eduinq File Truncated Successfully
Explanation
Uses FileChannel.truncate() to shorten file. - Keeps only first 10 bytes. - Exception handling ensures safe operations. - In enterprise systems, truncation manages file size limits. Conclusion: Shows truncating file with FileChannel.