public class FileInputStreamDemo {
public static void main(String[] args) {
}
/**
* 单个字节读取,效率低
*/
@Test
public void readFile01() {
String filePath = "D:\\test\\inputStream\\hello.txt";
int readData = 0;
try (FileInputStream inputStream = new FileInputStream(filePath)) { //字节流,读中文会乱码
while ((readData = inputStream.read()) != -1) { //-1代表读入结束
System.out.print((char) readData);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* read(byte[])字节读取,效率高
*/
@Test
public void readFile02() {
String filePath = "D:\\test\\inputStream\\hello.txt";
int readData = 0;
int bufLen;
byte[] buf = new byte[8]; // 字节数组
try (FileInputStream inputStream = new FileInputStream(filePath)) { //字节流,读中文会乱码
while ((bufLen = inputStream.read(buf)) != -1) { //将数据读入到buf中去
//最后一次读入的有效数据长度,不一定等于buf.length,所以得用bufLen响应式控制
System.out.print(new String(buf, 0, bufLen));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}