stream
文件流
文件的内容本质上都是来自于硬盘,而硬盘由操作系统管理.
使用java来操作文件,就要用到java的api.
这里涉及一系列的类:
字节流: InputStream和OutputStream是以操作字节为单位(二进制文件).
字符流: Reader和Write是以操作字符为单位(文本文件)
public static void main(String[] args) throws IOException {
try(InputStream inputStream = new FileInputStream("./testDir/test.txt")) {
while (true) {
byte[] bytes = new byte[1024];
int n =inputStream.read(bytes);
for (int i = 0; i < n; i++) {
System.out.printf("%x ", bytes[i]);
}
}
}
}
// hello file
// 68 65 6c 6c 6f 20 66 69 6c 65
字节数组存储read来的字节数据.
Scanner
在操作系统中, 操作系统是一个广义的概念,System.in也是一个特殊的文件,对应标准输入.
Scanner也可以来读取文本数据,把读到的字节数据进行转换.
Scanner只适用于读文本文件, 不适合读取二进制文件.
public static void main(String[] args) throws IOException{
try(InputStream inputStream = new FileInputStream("./testDir/test.txt")) {
Scanner scanner =