单个字节读取
package com.msb.io01;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Test04 {
public static void main(String[] args) throws IOException {
File f = new File("D:\\aa.png");
FileInputStream fis = new FileInputStream(f);
int read = fis.read();
int count = 0;//读取字节的计数器
while (read != -1){
System.out.println(read);
count++;//每读取一次,增加一次
read = fis.read();
}
System.out.println(count);//在文件属性中查看
fis.close();
}
}
用缓冲数组读取
package com.msb.io01;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Test05 {
public static void main(String[] args) throws IOException {
//1.获取文件
File f = new File("D:\\aa.png");
//2.装载文件
FileInputStream fis = new FileInputStream(f);
//3.读取文件
//(1)利用缓冲数组,
byte[] b = new byte[1024*6];
int len = fis.read(b);//读取数组中的有效长度,结尾处len=-1
while (len!=-1){
// System.out.println(len);
for (int i = 0; i < len; i++) {
System.out.println(b[i]);
}
len = fis.read(b);
}
fis.close();
}
}