Java FileChannel.getChannel()方法

原文:https://www.studytonight.com/java-file-io/java-fileinputstream-getchannel-method

在本教程中,我们将学习 JavaFileInputStream类的getChannel()方法。此方法用于返回与此FileInputStream相关联的离散文件通道对象。返回通道的位置是到目前为止从文件中读取的字节数。这是一种非静态方法,在 java.io 包中提供。

句法

这是此方法的语法声明。它不接受任何参数,并返回与此输入流链接的文件通道。

public FileChannel getChannel()

示例 Java 中的文件通道对象

在本例中,我们使用了文件通道类的 getChannel()方法,该方法返回文件通道的一个对象。

package com.studytonight;
import java.io.IOException;
import java.io.FileInputStream;
import java.nio.channels.FileChannel;
public class Studytonight {
   public static void main(String[] args) throws IOException {
      FileChannel fc = null;
      FileInputStream fis = null;
      int i = 0;
      long pos;
      char c;
      try {         
         fis = new FileInputStream("E:/Studytonight/output.txt");
         while((i = fis.read())!=-1) {
            fc = fis.getChannel();
            pos = fc.position();
            c = (char)i;
            System.out.print("No of bytes read: "+pos);
            System.out.println("; Char read: "+c);
         }
      } catch(Exception ex) {
         System.out.println("IOException: close called before read()");
      } finally {
         if(fis!=null)
            fis.close();
         if(fc!=null)
            fc.close();
      }
   }
}

输出. txt

CURIOUS

读取的字节数:1;字符读取:C 读取字节数:2;字符读取:U 读取的字节数:3;字符读取:R 读取字节数:4;字符读取:I 读取字节数:5;字符读取:0 读取字节数:6;字符读取:U 读取字节数:6;字符读数:S

示例 Java 中的文件通道对象

这是另一个用 Java 获取文件的 filechannel 对象的例子,我们可以用它来读写文件中的数据。

import java.io.*;
import java.nio.channels.*;
public class Studytonight {
 public static void main(String[] args) throws Exception {
  FileInputStream st = null;
  FileChannel std = null;
  int count = 0;
  try {
   st = new FileInputStream("E:\Studytonight\output.txt");
   while ((count = st.read()) != -1) {
    count = st.read();
    byte b = (byte) count;
    System.out.println("st.read(): " + b);
   }
   std = fis_stm.getChannel();
   System.out.println("st.getChannel(): " + std);
  } catch (Exception ex) {
   System.out.println(ex.toString());
  } finally {
   if (st != null) {
    st.close();
    if (std != null) {
     std.close();
    }
   }
  }
 }
}

ST . read():4 ST . read():97 ST . read():97 ST . read():8 ST . read():111 ST . read():108 ST . read():33 ST . read():33 ST . getchannel():sun . nio . ch . file channel mpl @ 31b 7 dea0

mail结论:

在本教程中,我们学习了 JavaFileInputStream类的getChannel()方法,该方法返回与当前FileInputStream相关联的特定文件通道。它只能用类对象访问,如果我们试图用类名访问方法,那么我们会得到一个错误。