package lesson.ls02;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import lesson.SD;
// 字节流读取中文(如何处理)
public class IO05 {
public static void main(String[] args){
String child = "io" + SD.S_F + "io02" + SD.S_F + "100.txt";
File file = new File(SD.D_W, child);
FileInputStream input = null;
try {
input = new FileInputStream(file);
// read(byte[] b)
// 1)一次最多读取b.length个字节(最后一次的读取长度为<=length)
// 2)读取的返回值是int类型的 读取的字节长度
// 3)没有数据可读是,返回-1
// 4)读取到的数据直接存储到byte[]中
int len = 0;
// ①
// 200.txt用utf-8编码规则,汉字占3个字节
// byte[] res = new byte[3];
// ②
// 300.txt用GBK编码规则,汉字占2个字节
// byte[] res = new byte[2];
// ③
// 100.txt中英文共存,如何定义byte[]一次读取的字节大小
// ③
// ArrayList<Integer> ls = new ArrayList<Integer>();
byte[] res = new byte[(int) (file.length())];
while ((len = input.read(res)) != -1) {
// System.out.println(len);
// ① MacOS系统默认编码,可以省略utf8
// System.out.print(new String(res, "utf8"));
// ②
// System.out.print(new String(res, "GBK"));
// ③
// for (int i = 0; i < len; i++) {
// ls.add(Integer.valueOf(res[i]));
// }
System.out.print(new String(res));
}
// ③
// byte[] result = new byte[ls.size()];
// for (int i = 0; i < result.length; i++) {
// result[i] = ls.get(i).byteValue();
// }
// System.out.println(new String(result));
} catch (FileNotFoundException e) {
System.err.println("异常 - FileNotFoundException");
} catch (IOException e) {
System.err.println("异常 - FileNotFoundException");
}
try {
if (input != null)
input.close();
} catch (IOException e) {
System.err.println("异常 - IOException");
}
}
}
字节流读取中文(如何处理)
最新推荐文章于 2025-06-01 18:29:20 发布