JAVA中的FileInputStream
- 1、文件字节输入流,万能的,任何类型的文件都可以采用这个方法
2、字节的方式,完成输入的操作,完成读的操作(硬盘 ——> 内存) - 可以使用byte[ ]数组的方式存储读取到的元素
public class FileInputStreamTest01 {
public static void main(String[] args) {
FileInputStream fls = null;
try {
//这里采用了绝对路径的方式,还可以采用相对路径 \\可写成/
fls = new FileInputStream("C:\\Users\\Lucky777\\IdeaProjects\\study\\src\\io\\tempfile.txt ");
//相对路径:
//fls = new FileInputStream("src\\io\\tempfile.txt");
//创建byte数组 一次读取4个数据
byte[] bytes = new byte[4];
int readCount = 0;
//read()方法返回读到数据的ASCII码
//read()方法调用一次读取一个字节
while ((readCount = fls.read(bytes)) != -1){
//使用String构造方法将byte[]数组转为字符串
System.out.println(new String(bytes,0,readCount));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
if (fls != null) {
try {
fls.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 设置相对路径的方法:
- read方法细节
//创建byte数组
byte[] bytes = new byte[4];
int readCount = fls.read(bytes);
System.out.println(readCount); //4 readCount存储的是读取的数据个数
//使用String构造方法将byte[]数组转为字符串
System.out.println(new String(bytes));
readCount = fls.read(bytes);
//新读取的数据覆盖旧数据,没读取到数据的位上的数据则不变
System.out.println(readCount); //2
//不应该全部转换成String,应该读取多少转多少
System.out.println(new String(bytes,0,readCount));
-
FileInputStream类的两个常用方法:
int available(); 返回流中剩余的没有读取到的字节数量
long skip(long n); 跳过n个字节不读取 -
可以直接创建一个fls.available大小的byte[ ]数组来一次性读出数据
但不适用于大数据,因为会超出byte[ ]数组范围
public class FileInputStreamTest04 {
public static void main(String[] args) {
FileInputStream fls = null;
try {
fls = new FileInputStream("src\\io\\IOReadme.txt");
//使用skip()方法,跳过2个字节再读取
// fls.skip(2);
//使用available()方法
//因为还没进行读取,所以可以直接创建一个fls.available大小的数组
//但不适用于大数据
byte[] bytes = new byte[fls.available()];
//只需读一次就够了
int readCount = fls.read(bytes);
System.out.println(new String(bytes,0,readCount));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fls != null) {
try {
fls.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}