官网API:
https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html
public static void main(String[] args) throws IOException {
getConstructor();
//getLoanShift();
//getLoanShiftThree();
}
/**
* read(byte[],int off,int len),和read(byte[] b)差不多
*/
private static void getLoanShiftThree() throws IOException {
FileInputStream fis = new FileInputStream(new File("D:\\a.txt"));
byte[] b = new byte[2];
int len = 0;
while((len = fis.read(b, 0, b.length)) != -1){
System.out.print(new String( b, 0, len));
}
fis.close();
}
/**
* read(byte[] b) 返回读取到的字节数
* 如果byte数组字节数为2,文件内容为abcde,2个字节依次读取三次那么读取结果就abcded
* 第一次:byte{a,b},第二次:byte{c,d},第三次:byte{e,d},覆盖式的写入,最后一个没有了所以d没有被覆盖写入遗留的,byte数组读取到的字节数为2,2,1
* 使用String的构造方法来完成:String(要读取的数组,开始位置,结束位置);这样读取的就是2,2,1,字符是ab,cd,e
*/
private static void getLoanShift() throws IOException {
FileInputStream fis = new FileInputStream(new File("D:\\a.txt"));
byte[] b = new byte[2];//一般写入字节数为1024或者倍数,建议别太大,太消耗内存
int len = 0;
while ((len = fis.read(b)) != -1) {
System.out.print(new String(b, 0, len));
}
fis.close();
}
/**
* 构造参数:File,String read()
*/
private static void getConstructor() throws IOException {
FileInputStream fis = new FileInputStream("D:\\a.txt");
int data = 0; // 接受数据,如果定义fis.read()成为一个变量使用变量来循环则是死循环,所以必须循环内读取,但是数据拿不到,所以每次执行使用变量接受读取到的值,然后判断
while ((data = fis.read()) != -1) { // 返回下一个数据字节int,或者-1如果到达文件末尾。
System.out.println(data); // 可以强转为char即可显示ASCLL码表的转码
}
fis.close();
}