java - 读取UTF8文件(在记事本上创建)并转换为CP850字符串

标签 java decode encode utf codepages

我正在尝试读取 UTF8 文件并将其转换为 CP850(以发送到打印机设备)。 我的测试字符串是“ATIVAÇãO”

A    T    I    V    A    Ç         Ã       O
0x41 0x54 0x49 0x56 0x41 0xC3 0x87 C3 0x83 4F

我的java代码:

private static void printBytes(String s, String st) {
    byte[] b_str = s.getBytes();
    System .out.print(String.format("%-7s >>> ", st));
    for (int i=0; i<s.length();i++)
        System.out.print(String.format("%-7s ", s.charAt(i)));
    System.out.println();

    System .out.print(String.format("%-7s >>> ", st));
    for (int i=0; i<b_str.length;i++)
        System.out.print(String.format("0x%-5x ", (int)b_str[i] & 0xff));
    System.out.println();
}

public static void main(String [] args) throws Exception, Exception {

    String F="file.txt";

    InputStreamReader input = new InputStreamReader(new FileInputStream(F));
    BufferedReader in = new BufferedReader(input);

    String strFILE;
    String strCP850;

    while ((strFILE = in.readLine()) != null) {

        strFILE = strFILE.substring(3);
        printBytes(strFILE, "ORI");
        strCP850 = new String(strFILE.getBytes(), "CP850");
        printBytes(strCP850, "CP850");
        System.exit(0);
    }

    in.close();

}

输出:

ORI     >>> A       T       I       V       A       Ã       ‡       Ã       ƒ       O       
ORI     >>> 0x41    0x54    0x49    0x56    0x41    0xc3    0x87    0xc3    0x83    0x4f    
CP850   >>> A       T       I       V       A       ?       ç       ?       â       O      
CP850   >>> 0x41    0x54    0x49    0x56    0x41    0x3f    0xe7    0x3f    0xe2    0x4f   

我是expecting “Ç”为 0xc7,“à”为 0xc3,但转换结果为两字节字符(如 utf8...)。

我做错了什么?

有办法做到这一点(jdk 1.6)吗?

最佳答案

首先:String没有编码。然而,正确执行的重要一点是在将文件读取为文本时指定编码。

为了读取 UTF-8 格式的文件,然后将其转储为 cp850:您可以这样做:

final Path path = Paths.get("file.txt");

try (
    final BufferedReader reader = Files.newBufferedReader(path,
        StandardCharsets.UTF_8);
) {
    String line;
    byte[] bytes;
    while ((line = reader.readLine()) != null) {
        bytes = line.getBytes(Charset.forName("cp850"));
        // write this method
        dumpBytes(bytes);
    }
}

关于java - 读取UTF8文件(在记事本上创建)并转换为CP850字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27609018/

相关文章:

java - @StepScope 是否可以与 @Conditional 和 jobParameters 一起使用?

java - 依赖项(Jar 文件)中的类未解析,导致编译错误

java - 如何在 Java 中取消转义 HTML 字符实体?

Javascript 高级 Unicode 编码/解码

file - Angular 2 将图像编码为 base64

android - 在 APK 中编码/解码 AndroidManifest.xml

java - 如何在 Kotlin 中为 @PropertySource 创建 Java 数组?

java - 如何通过正则表达式从 pmd 规则中排除类

mysql - 从数据库返回解码后的文本

ffmpeg - 使用ffmpeg将图像转换为gif时如何设置帧延迟