import java.io.*; public class FileLengthDemo { public static void main(String[] args) { try { // Create a RandomAccessFile object RandomAccessFile raf = new RandomAccessFile("example.txt", "rw"); // Set the length of the file to 50 bytes raf.setLength(50); // Close the file raf.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }In this example, we create a RandomAccessFile object for the file "example.txt" with "rw" mode. Then, we call the setLength() method to set its length to 50 bytes. Finally, we close the file. The setLength() method belongs to java.io package.