Java教程

Java 将文件加载为 InputStream 的程序

将文件加载为 InputStream 的 Java 程序

在本例中,我们将学习使用 Java 中的 FileInputStream 类将文件作为输入流加载。
要理解此示例,您应该了解以下Java 编程主题:
Java 文件类 Java InputStream 类 Java FileInputStream 类

示例 1: 将文本文件加载为 InputStream 的 Java 程序

import java.io.InputStream;
import java.io.FileInputStream;
public class Main {
  public static void main(String args[]) {
    try {
      // file input.txt is loaded as input stream
      // input.txt file contains:
      // this is a content of the file input.txt
      InputStream input = new FileInputStream("input.txt");
      System.out.println("Data in the file: ");
      // Reads the first byte
      int i = input.read();
      while(i !=-1) {
        System.out.print((char)i);
        // Reads next byte from the file
        i = input.read();
      }
      input.close();
    }
    catch(Exception e) {
      e.getStackTrace();
    }
  }
}
输出
Data in the file: 
this is a content of the file input.txt.
在上面的示例中,我们有一个名为 input.txt 的文件。文件内容为
this is a content of the file input.txt.
在这里,我们使用了 FileInputStream 类来加载 input.txt 文件作为输入流。然后我们使用 read() 方法从文件中读取所有数据。

示例 2: 将 Java 文件加载为 InputStream 的 Java 程序

假设我们有一个名为 Test.java 的 Java 文件,
class Test {
  public static void main(String[] args) {
    System.out.println("this is Java File");
  }
}
我们也可以加载这个 Java 文件作为输入流。
import java.io.InputStream;
import java.io.FileInputStream;
public class Main {
  public static void main(String args[]) {
    try {
      // file Test.java is loaded as input stream
      InputStream input = new FileInputStream("Time.java");
      System.out.println("Data in the file: ");
      // Reads the first byte
      int i = input.read();
      while(i !=-1) {
        System.out.print((char)i);
        // Reads next byte from the file
        i = input.read();
      }
      input.close();
    }
    catch(Exception e) {
      e.getStackTrace();
    }
  }
}
输出
Data in the file: 
class Test {
  public static void main(String[] args) {  
    System.out.println("this is Java File");
  }
}
在上面的例子中,我们使用了 FileInputStream 类来加载 Java 文件作为输入流。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4