import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class InputStreamDemo {
/*
* InputStream字节输入流
* FileInputStream:文件字节输入流
* --->构造方法
* 1.new FileInputStream(File file):
* 传入File对象,代表了文件源
* 2.new FileInputStream(String name):
* 传入String类型的文件路径,该路径代表的文件是文件源。
*/
public static void main(String[] args) {
File file = new File("D:/test/a.txt");
InputStream is = null;
try {
is= new FileInputStream(file);
/*
* int|read():一次一个字节,返回int Unicode编码表
*/
/*int i = is.read();
System.out.println(i);
*/
/*
* int | read(byte[] bytes):把读取到的内容存入byte数组中,
* 返回值为每次读取到的字节的个数。如果不存在则返回-1
*/
/* String str = "";
int len = 0;
byte[] bytes = new byte[3];
while((len = is.read(bytes)) != -1){//还有剩余内容
//System.out.println(Arrays.toString(bytes));
String s = new String(bytes,0,len);
str += s;
}
System.out.println(str);
*/
/*
* int | read(byte[] bytes , int off,int len):
* 把读取到的内容存入bytes数组中,每次从下标为off开始
* 最多存储len个,返回值为每次读取到的字节的个数。
* 如果读取不到内容则返回-1
*/
byte[] bytes = new byte[3];
String str = "";
int len = 0;
while((len = is.read(bytes, 1, 2)) != -1){
String s = new String(bytes,1,len);
str += s;
}
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
InputStream 简介
最新推荐文章于 2025-10-14 12:07:22 发布
本文详细介绍了Java中使用FileInputStream进行文件字节流读取的方法,包括构造方法的使用,以及如何通过read方法逐字节或按字节数组读取文件内容,并展示了完整的代码示例。
4245

被折叠的 条评论
为什么被折叠?



