Java IO FileInputStream 解析

举报
张俭 发表于 2023/12/29 14:01:25 2023/12/29
【摘要】 java.io.FileInputStream是InputStream的具体实现,提供具体文件的输入流 public class FileInputStream extends InputStreamFileInputStream 实现了InputStream的常用方法 public int read() throws IOException public int read(byte[...

java.io.FileInputStream是InputStream的具体实现,提供具体文件的输入流

  public class FileInputStream extends InputStream

FileInputStream 实现了InputStream的常用方法

  public int read() throws IOException
  public int read(byte[] data) throws IOException
  public int read(byte[] data, int offset, int length) throws IOException
  public native long skip(long n) throws IOException
  public native int available() throws IOException
  public native void close() throws IOException

这些方法都是Java Native Code,除了read方法,但这些方法还是把参数传给了native方法。所以实际上,这些方法都是Native方法。
FileInputStream有三种构造方法,区别在于文件是如何指定的:

  public FileInputStream(String fileName) throws IOException
  public FileInputStream(File file) throws FileNotFoundException
  public FileInputStream(FileDescriptor fdObj)

第一个构造函数使用文件的名称,文件的名称跟平台相关,所以硬编码文件名不是一个好的方案,相比之下,后两个就要好很多。
读取文件,我们只需要把文件名称传递给构造函数。然后像平常那样调用read方法即可。

  FileInputStream fis = new FileInputStream("README.TXT");
  int n;
  while ((n=fis.available())>0) {
    byte[] b = new byte[n];
    int result = fis.read(b);
    if( result == -1) break;
    String s = new String(b);
    System.out.print(s);
   }

Java在当前的工作路径寻找文件,通常来说,就是你键入java programName时的路径。在FileInputStream的构造函数中传入相对路径和绝对路径都是可行的。
如果你试图打开一个并不存在的文件,就会抛出FileNotFoundException。如果因为其他原因无法写入(比如权限不足)其他类型的异常会被抛出。下面是一个通过控制台获取文件名,然后把文件打印到控制台的例子

public class FileTyper {
  public static void main(String[] args) {
    if(args.length==0) {
      System.err.println("no file is determined");
      return;
    }
    for (int i=0;i<args.length;i++) {
      try{
        typeFile(args[i]);
        if(i+1<args.length) {
          System.out.println();
          System.out.println("--------");
        }
       } catch (IOException e) {System.err.println(e);}
     }
  }
  public static void typeFile(String filename) throws IOException {
    FileInputStream fin = new FileInputStream(filename);
    StreamCopier.copy(fin,System.out);
    fin.close();
  }
}

如果需要的话,你也可以对同一个文件同时打开多个流。每一个流维护一个单独的指针,指向文件中的当前位置。读取文件并不会更改文件,如果是写文件的话,那就是另一回事了。

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。