JAVA读取文件里面部分汉字内容乱码

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/u013041642/article/details/80368787

JAVA读取文件里面部分汉字内容乱码

读取一个txt文件,到代码中打印出来,发票有部分汉字的内容是乱码的。我开始的方式是这样的, 如下,这是完全错误的,汉字是两个字节的,如果每次读固定个字节,可能会把汉字截断。就会出现部分乱码的情况。

package susq.path;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author susq
 * @since 2018-05-18-19:28
 */
public class WrongMethodReadTxt {
    public static void main(String[] args) throws IOException {
        ClassLoader classLoader = WrongMethodReadTxt.class.getClassLoader();
        String filePath = classLoader.getResource("").getPath() + "/expect1.txt";

        System.out.println(filePath);

        File file = new File(filePath);
        try (FileInputStream in = new FileInputStream(file)) {
            byte[] bytes = new byte[1024];
            StringBuffer sb = new StringBuffer();
            int len;
            while ((len = in.read(bytes)) != -1) {
                sb.append(new String(bytes, 0, len));
            }
            System.out.println(sb.toString());
        }
    }
}

如果存在汉字,就要按字符的方式读取:


package susq.path;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author susq
 * @since 2018-05-18-17:39
 */
public class SysPath {
    public static void main(String[] args) throws IOException {
        ClassLoader classLoader = SysPath.class.getClassLoader();
        String filePath = classLoader.getResource("").getPath() + "/expect1.txt";

        System.out.println(filePath);

        File file = new File(filePath);
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            StringBuffer sb = new StringBuffer();
            while (br.ready()) {
                sb.append(br.readLine());
            }
            System.out.println(sb);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u013041642/article/details/80368787