Java.io.RandomAccessFile.setLength() 方法



描述

java.io.RandomAccessFile.setLength(long newLength) 方法設定此檔案的長度。

宣告

以下是 java.io.RandomAccessFile.setLength() 方法的宣告。

public void setLength(long newLength)

引數

newLength − 檔案所需的長度

返回值

此方法不返回值。

異常

IOException − 如果發生 I/O 錯誤。

示例

以下示例演示了 java.io.RandomAccessFile.setLength() 方法的用法。

package com.tutorialspoint;

import java.io.*;

public class RandomAccessFileDemo {
   public static void main(String[] args) {
   
      try {
         // create a new RandomAccessFile with filename test
         RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

         // write something in the file
         raf.writeUTF("Hello World");

         // set the file pointer at 0 position
         raf.seek(0);

         // print the string
         System.out.println("" + raf.readUTF());

         // print current length
         System.out.println("" + raf.length());

         // set the file length to 30
         raf.setLength(30);

         // print the new length
         System.out.println("" + raf.length());
         
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

假設我們有一個文字檔案 c:/test.txt,其內容如下。此檔案將用作我們示例程式的輸入。

ABCDE  

讓我們編譯並執行上述程式,這將產生以下結果:

Hello World
13
30
java_io_randomaccessfile.htm
廣告
© . All rights reserved.