当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Java.io.RandomAccessFile.getChannel()用法及代码示例



描述

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

声明

以下是声明java.io.RandomAccessFile.getChannel()方法。

public final FileChannel getChannel()

参数

NA

返回值

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

异常

NA

示例

下面的例子展示了使用java.io.RandomAccessFile.getChannel()方法。

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);

         // 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();
      }
   }
}

假设我们有一个文本文件c:/test.txt,其内容如下。这个文件将用作我们示例程序的输入——

ABCDE  

让我们编译并运行上面的程序,这将产生以下结果——

Hello World
sun.nio.ch.FileChannelImpl@3d4b7453

相关用法


注:本文由纯净天空筛选整理自 Java.io.RandomAccessFile.getChannel() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。