Java 程序:将文件加载为 InputStream

要理解此示例,您应了解以下Java编程主题


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

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 程序将 Java 文件加载为 InputStream

假设我们有一个名为 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 文件加载为输入流。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战