示例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文件加载为输入流。