首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >为什么GBK编码的文件与UTF-8文本相比是相同的?

为什么GBK编码的文件与UTF-8文本相比是相同的?
EN

Stack Overflow用户
提问于 2022-07-20 02:32:41
回答 1查看 81关注 0票数 0

我使用InputStreamReader来读取GBK编码txt,我认为lineTxt也会被GBK编码,但是当我比较"WGS 84 / UTM区域44N“时,它们是相同的。

以下是代码:

1、s是UTF-8编码的字符串。

2、lineTxt是GBK编码的字符串(我不确定,但我知道"read“是GBK)

3我猜"lineTxt = bufferedReader.readLine()“如果编码,将触发转换,但不确定。

代码语言:javascript
代码运行次数:0
运行
复制
try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), ENCODING_GBK);
         BufferedReader bufferedReader = new BufferedReader(read)) {
        String lineTxt;
        while ((lineTxt = bufferedReader.readLine()) != null) {
            if (lineTxt.contains("WGS 84 / UTM zone 44N")) {
                String s = new String("输出坐标系:WGS 84 / UTM zone 44N".getBytes(), StandardCharsets.UTF_8);
                System.out.println(System.getProperty("file.encoding"));
                System.out.println(Arrays.toString(s.getBytes()));
                System.out.println(Arrays.toString(lineTxt.getBytes()));
            }
        }
    } catch (IOException e) {
        log.error("Read file failed");
        e.printStackTrace();
    }
EN

回答 1

Stack Overflow用户

发布于 2022-08-14 08:36:34

当读取文件并将行存储为字符串对象时,编码将转换为字符串的内部表示形式(UTF-16)。lineTxt.getBytes()在平台的默认编码中将UTF-16字符串转换为字节数组(这取决于在Windows上的系统区域设置。当你在另一个月台的时候,它将是UTF-8 )。

如果要将文件的内容获取为字节数组(获取GBK表示形式,并且不希望将内容转换为UTF-16),请按以下方式读取该文件:

代码语言:javascript
代码运行次数:0
运行
复制
try {
    File file = new File("C:\\tmp\\fileGBK.txt");
    byte[] lineTxt = Files.readAllBytes(file.toPath());
    System.out.println(Arrays.toString(lineTxt));
} catch (IOException e) {
    e.printStackTrace();
}

您将得到GBK ([-54, -28, -77, -10, -41, ...)中字符串的表示形式。

如果要逐个读取文件中的行并获取行的GBK表示形式:

代码语言:javascript
代码运行次数:0
运行
复制
File file = new File("C:\\tmp\\fileGBK.txt");
final Charset ENCODING_GBK = Charset.forName("GBK");
try (InputStreamReader read = new InputStreamReader(new FileInputStream(file), ENCODING_GBK);
        BufferedReader bufferedReader = new BufferedReader(read)) {
    String lineTxt;
    while ((lineTxt = bufferedReader.readLine()) != null) {
        if (lineTxt.contains("WGS 84 / UTM zone 44N")) {
            String s = new String("输出坐标系:WGS 84 / UTM zone 44N".getBytes(), StandardCharsets.UTF_8);
            System.out.println(System.getProperty("file.encoding"));
            System.out.println(Arrays.toString(s.getBytes()));
            System.out.println(Arrays.toString(lineTxt.getBytes(ENCODING_GBK)));
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73045377

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档