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.

Source Code

1 import java.io.*;
2 import java.nio.channels.*;
3 public class FileChannelTruncateExample {
4 public static void main(String[] args) {
5 System.out.println("Eduinq FileChannel Truncate Example");
6 try(RandomAccessFile raf=new RandomAccessFile("sample.txt","rw");
7 FileChannel fc=raf.getChannel()) {
8 fc.truncate(20);
9 System.out.println("Eduinq File Truncated to 20 bytes");
10 } catch(Exception e){ System.out.println("Eduinq Exception: "+e.getMessage()); }
11 }
12 }

Program Output

					Eduinq FileChannel Truncate Example
Eduinq File Truncated to 20 bytes
				

Explanation

Uses truncate() to reduce file size. - Removes data beyond specified length. - Exception handling ensures safe operations. - In enterprise systems, truncation manages log file size. Conclusion: Shows truncating files with FileChannel.

Quick Links to Explore