使用 InputStream 读取文件的 Java 程序
要理解此示例,您应具备以下 Java 编程的知识:
示例 1:将文本文件加载为 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 文件加载为 InputStream
考虑我们有一个名为 Test.java
的 Java 文件,
public 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 文件作为输入流加载。