java 获取文件流InputStream
时间: 2024-03-06 07:42:50 浏览: 138
以下是Java获取文件流InputStream的两种方法:
1. 使用FileInputStream类读取文件流
```java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ReadFile {
public static void main(String[] args) {
try {
InputStream inputStream = new FileInputStream("example.txt");
int n;
while ((n = inputStream.read()) != -1) {
System.out.print((char) n);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 使用ClassLoader类获取文件流
```java
import java.io.IOException;
import java.io.InputStream;
public class ReadFile {
public static void main(String[] args) {
try {
InputStream inputStream = ReadFile.class.getClassLoader().getResourceAsStream("example.txt");
int n;
while ((n = inputStream.read()) != -1) {
System.out.print((char) n);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文