Java RandomAccessFile getChannel()方法

java.io.RandomAccessFile.getChannel() 方法返回与此文件关联的唯一文件通道对象。

1 语法

public final FileChannel getChannel()

2 参数

3 返回值

此方法返回与此文件关联的文件通道

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.RandomAccessFile.getChannel()方法的例子
 */
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());

            // return the channel of the file
            System.out.println("" + raf.getChannel());

            // close the strea and release resources
            raf.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

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

ABCDE  

输出结果为:

Hello World
sun.nio.ch.FileChannelImpl@4554617c

热门文章

优秀文章