### FileInputStream读取一个字节
```
ppublic class FileInputStreamTest1 {
public static void main(String[] args) {
try (
//1.创建文件字节输入流管道,与源文件接通
FileInputStream fis = new FileInputStream("要读文件路径");
) {
// 2、开始读取文件的字节数据
int b;// 用于记住读取的字节
while ((b = fis.read()) != -1) {
System.out.print((char) b);
}
} catch (IOException e) {
e.printStackTrace();
}
// //3、流使用完毕之后,必须关闭!释放系统资源!
// fis.close();
}
}
```
### FileInputStream读取多个字节
```
public static void main(String[] args) throws IOException {
//1.创建文件字节输入流管道,与源文件接通
FileInputStream fis = new FileInputStream("要读文件路径");
// 2、开始读取文件中的字节数据:每次读取多个字节(可变)
一般是1024个字节
byte[] b = new byte[1024];
int len;//记住每次读取了多少个字节
while ((len = fis.read(b)) != -1) {
String s = new String(b, 0, len);
System.out.println(s);
}
//关闭流
fis.close();
}
```
### FileInputStream读取全部字节
```
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("要读文件路径");
//开始读取文件中的字节数据:读取全部字节
byte[] bytes = fis.readAllBytes();
String s = new String(bytes);
System.out.println(s);
}
```
FileInputStream读取字节
最新推荐文章于 2024-02-18 17:03:14 发布