Java RandomAccessFile close()方法

java.io.RandomAccessFile.close() 方法关闭此随机存取文件流并释放与该流关联的所有系统资源。一个封闭的随机访问文件不能执行输入或输出操作,并无法重新打开。

1 语法

public void close()

2 参数

3 返回值

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.RandomAccessFile.close()方法的例子
 */
import java.io.*;

public class Demo {
    public static void main(String[] args) {

        try {
            // create a new RandomAccessFile with filename test
            RandomAccessFile raf = new RandomAccessFile("d:/test.txt", "rw");

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

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

            // read and print the contents of the file
            System.out.println("" + raf.readUTF());

            // close the strea and release resources
            System.out.println("Closing Stream...");
            raf.close();
            System.out.println("Stream Closed.");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

假设test.txt文件内容如下:

ABCDE 

输出结果为:

Hello World
Closing Stream...
Stream Closed.

热门文章

优秀文章