Java:将 UTF8 字符串转换为另一种编码的字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4022240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:33:33  来源:igfitidea点击:

Java: convert UTF8 String to byte array in another encoding

javaencodingcp1251

提问by Pavel Vyazankin

I have UTF8 encoded String, but I need to post parameters to Runtime process in cp1251. How can I decode String or byte array?

我有 UTF8 编码的字符串,但我需要将参数发布到 cp1251 中的运行时进程。如何解码字符串或字节数组?

I need smth like:.bytesInCp1251 = encodeTo(stringInUtf8, "cp1251");

我需要像:。bytesInCp1251 = encodeTo(stringInUtf8, "cp1251");



Thanks to all! This is my own solution:

谢谢大家!这是我自己的解决方案:

OutputStreamWriter writer = new OutputStreamWriter(out, "cp1251");
writer.write(s);

采纳答案by Michael Borgwardt

There is no such thing as an "UTF8 encoded String"in Java. Java Strings use UTF-16 internally, but should be seen as an abstraction without a specific encoding. If you have a String, it's already decoded. If you want to encode it, use string.getBytes(encoding). If you original data is UTF-8, you have to take that into account when you convert that data from bytes to String.

Java 中没有“UTF8 编码字符串”这样的东西。Java 字符串在内部使用 UTF-16,但应将其视为没有特定编码的抽象。如果你有一个字符串,它已经被解码了。如果要对其进行编码,请使用string.getBytes(encoding). 如果原始数据是 UTF-8,则在将该数据从字节转换为字符串时必须考虑到这一点。

回答by Buhake Sindi

Why not do something like this (assuming stringInUtf8is a UTF-8 String)?

为什么不做这样的事情(假设stringInUtf8是一个 UTF-8 字符串)?

String cp1251Str = new String(stringInUtf8.getBytes("UTF-8"), "cp1251");

回答by William

byte[] bytesInCp1251 = stringInUtf8.getBytes("cp1251");

回答by Pavel Vyazankin

This is solution!

这是解决方案!

OutputStreamWriter writer = new OutputStreamWriter(out, "cp1251");
writer.write(s);