java FileInputStream
(12.1)FileInputStream将文件读入作为流来处理,有两种实例化方式
// 方式1 FileInputStream fis = new FileInputStream("./learn.txt"); // 方式2 File f = new File("./learn.txt"); FileInputStream fis = new FileInputStream(f);
(12.2) java FileInputStream.read方法
java FileInputStream.read默认读取的是文件的一个字节,并且返回的是二进制代表的字符编码,还需要转换下才能正常显示
File f = new File("./learn.txt"); FileInputStream fis = new FileInputStream(f); while (true) { int num = fis.read(); if (num != -1) { System.out.println((char) num); } else { break; } }
(12.3) java FileInputStream.read[byte b]方法
从文件中读取b.length个字节到b中,例如
File f = new File("./learn.txt"); FileInputStream fis = new FileInputStream(f); byte[] b = new byte[10]; int number = fis.read(b); System.out.println("读取到" + number + "字节"); System.out.println(Arrays.toString(b)); fis.close();
文件内容如下:
1
2
总共读取到7个字节输出内容为:
[49, 13, 10, 50, 0, 0, 0, 0, 0, 0]
49 ASCII对应为1
13 ASCII对应为回车
10 ASCII对应为换行
50 ASCII对应为2