对于InputStream读取中文乱码,下面这段话给出了很好的解释,以及后续编码上的扩展。
BufferedInputStream和BufferedOutputStream是过滤流,需要使用已存在的节点来构造。
即必须先有InputStream或OutputStream,相对直接读写,这两个流提供带缓存的读写,提高了系统读写效率性能。
BufferedInputStream读取的是字节byte,因为一个汉字占两个字节,而当中英文混合的时候,有的字符占一个字节,有的字符占两个字节。
所以如果直接读字节,而数据比较长,没有一次读完的时候,很可能刚好读到一个汉字的前一个字节,这样,这个中文就成了乱码,后面的数据因为没有字节对齐,也都成了乱码。
所以我们需要用BufferedReader来读取,它读到的是字符,所以不会读到半个字符的情况,不会出现乱码。
1 package com.read;
2
3 import java.io.*;
4
5 /**
6 *千字文.txt 在 classpath 用来测试
7 */
8 public class Main {
9
10 public static void main(String[] args) {
11
12 File file = new File("千字文.txt");
13
14 Object obj = loadFileContent(file);
15 if (obj!=null){
16 System.out.println(obj.toString());
17 }
18 }
19
20 /**
21 * 此方法 读到的是字符,所以不会读到半个字符的情况,不会出现乱码.
22 * @param file
23 * @return
24 */
25 public static Object readFile(File file) {
26 StringBuilder buffer = new StringBuilder();
27 try {
28 if (!file.exists()) {
29 return null;
30 }
31
32 InputStream inputStream = new FileInputStream(file);
33 BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
34 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
35
36 while (bufferedReader.ready()) {
37 buffer.append((char) bufferedReader.read());
38 }
39
40 bufferedReader.close();
41 bufferedInputStream.close();
42 inputStream.close();
43
44 return buffer.toString();
45 } catch (FileNotFoundException e) {
46 e.printStackTrace();
47 return null;
48 } catch (IOException e) {
49 e.printStackTrace();
50 return null;
51 }
52 }
53
54 /**
55 * byte字节流读取文件时 一个汉字占2个字节
56 * 可能只能读到半个 时长度没有一次读完时 字符无法对齐
57 * 出现乱码 可能会是以上原因
58 * @param file
59 * @return
60 */
61 public static Object loadFileContent(File file) {
62 StringBuffer buffer = new StringBuffer();
63 try {
64
65 if (!file.exists()) {
66 return null;
67 }
68
69 InputStream inputStream = new FileInputStream(file);
70 byte[] bytes = new byte[1024];
71 int length;
72
73 while ((length = inputStream.read(bytes)) != -1) {
74 buffer.append(new String(bytes, 0, length));
75 }
76
77 inputStream.close();
78
79 return buffer.toString();
80 } catch (FileNotFoundException e) {
81 e.printStackTrace();
82 return null;
83 } catch (IOException e) {
84 e.printStackTrace();
85 return null;
86 }
87 }
88 }