我有一个带有“ñ”字符的字符串,但我遇到了一些问题。我需要将此字符串编码为 UTF-8 编码。我已经按照这个方法尝试过了,但是不行:
byte ptext[] = myString.getBytes();
String value = new String(ptext, "UTF-8");
如何将该字符串编码为 utf-8?
使用怎么样
ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(myString)
String
Java 中的对象使用无法修改的 UTF-16 编码*。
唯一可以有不同编码的是
byte[]
。因此,如果您需要 UTF-8 数据,那么您需要一个 byte[]
。如果您的 String
包含意外数据,那么问题出在较早的某个位置,错误地将一些二进制数据转换为 String
(即它使用了错误的编码)。
* 作为实现问题,当字符范围适合时,
String
可以在内部使用 ISO-8859-1 编码的 byte[]
,但这是特定于实现的优化,用户不可见String
(即,除非您深入研究源代码或使用反射来深入研究
String
对象,否则您永远不会注意到)。
import static java.nio.charset.StandardCharsets.*;
byte[] ptext = myString.getBytes(ISO_8859_1);
String value = new String(ptext, UTF_8);
这比
getBytes(String)
的优点是它不声明
throws UnsupportedEncodingException
。如果您使用的是较旧的 Java 版本,您可以自己声明字符集常量:
import java.nio.charset.Charset;
public class StandardCharsets {
public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
public static final Charset UTF_8 = Charset.forName("UTF-8");
//....
}
byte[] ptext = String.getBytes("UTF-8");
而不是
getBytes()
。
getBytes()
使用所谓的“默认编码”,可能不是UTF-8。
因此,如果您遇到编码问题,那么当您拥有 String 时,修复就为时已晚了。您需要修复从文件、数据库或网络连接创建该字符串的位置。
byte ptext[] = myString.getBytes("ISO-8859-1");
String value = new String(ptext, "UTF-8");
首先我需要导入
import java.nio.charset.Charset;
然后我必须声明一个常量来使用
UTF-8
和
ISO-8859-1
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final Charset ISO = Charset.forName("ISO-8859-1");
然后我可以通过以下方式使用它:
String textwithaccent="Thís ís a text with accent";
String textwithletter="Ñandú";
text1 = new String(textwithaccent.getBytes(ISO), UTF_8);
text2 = new String(textwithletter.getBytes(ISO),UTF_8);
String value = new String(myString.getBytes("UTF-8"));
并且,如果您想从编码为“ISO-8859-1”的文本文件中读取:
String line;
String f = "C:\\MyPath\\MyFile.txt";
try {
BufferedReader br = Files.newBufferedReader(Paths.get(f), Charset.forName("ISO-8859-1"));
while ((line = br.readLine()) != null) {
System.out.println(new String(line.getBytes("UTF-8")));
}
} catch (IOException ex) {
//...
}
String text = "This is an example é";
byte[] byteText = text.getBytes(Charset.forName("UTF-8"));
//To get original string from byte.
String originalString= new String(byteText , "UTF-8");
NetBeans 默认编码 UTF-8 分步指南
(示例:
netbeans_default_options="-J-Dfile.encoding=UTF-8"
)
您的 netbeans_default_options 可能在引号内包含其他参数。在这种情况下,请在字符串末尾添加 -J-Dfile.encoding=UTF-8。与其他参数用空格分开。
示例:
netbeans_default_options="-J-client -J-Xss128m -J-Xms256m -J-XX:PermSize=32m -J-Dapple.laf.useScreenMenuBar=true -J-Dapple.awt.graphics.UseQuartz=true -J-Dsun.java2d.noddraw=true -J-Dsun.java2d.dpiaware=true -J-Dsun.zip.disableMemoryMapping=true -J-Dfile.encoding=UTF-8"这里是链接
String inputText = "some text with escaped chars"
InputStream is = new ByteArrayInputStream(inputText.getBytes("UTF-8"));
String myUTF8String = new String(sourceISOString.getBytes(Charsets.ISO_8859_1), Charsets.UTF_8);