FileInputStream中其他常用方法——int available()
一、int available()方法
返回流当中剩余的没有读到的字节数量
二、代码展示
1.框架
框架很注重要,一定要会搭
package IO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest05 {
public static void main(String[] args) {
FileInputStream fis =null;
try {
fis = new FileInputStream("temp");
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2.被读取文件展示
为了便于理解,文件中仅有a b c d e f五个英文小写字符
3.方法使用
作用一:展示流当中剩余的没有读到的字节数量
package IO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/*
int available():返回流当中剩余的没有读到的字节数量
*/
public class FileInputStreamTest05 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("temp");
System.out.println("总字节数:"+ fis.available());
//读一个字节
int readByte = fis.read();
//还剩下可以读的字节数量:5
System.out.println("剩下多少个字节没有读:"+fis.available());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
执行结果:
作用二:可直接读取文件,不需要循环
package IO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStreamTest05 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("temp");
System.out.println("总字节数:"+ fis.available());
byte[] bytes = new byte[fis.available()];
int readCount = fis.read(bytes);//6
System.out.println(new String(bytes));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
注意:使用这种方法不能读太大的文件,因为byte[]数组在内存中不能太大,过大会占用过多的内存。