我有一个“ñ”字符的字符串,我有一些问题。我需要将这个字符串编码为UTF-8编码。我试过这种方法,但行不通:

byte ptext[] = myString.getBytes();
String value = new String(ptext, "UTF-8");

如何将该字符串编码为utf-8?


当前回答

你可以试试这种方法。

byte ptext[] = myString.getBytes("ISO-8859-1"); 
String value = new String(ptext, "UTF-8"); 

其他回答

怎么使用呢?

ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(myString)

使用byte[] ptext = String.getBytes("UTF-8");而不是getBytes()。getBytes()使用所谓的“默认编码”,可能不是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);

如何配置NetBeans默认编码UTF-8的快速分步指南。结果NetBeans将创建UTF-8编码的所有新文件。

NetBeans默认编码UTF-8分步指南

进入NetBeans安装目录下的etc文件夹 编辑netbeans.conf文件 找到netbeans_default_options行 添加-J-Dfile。encoding=UTF-8在这一行的引号内 (例如:netbeans_default_options =“-J-Dfile.encoding = utf - 8”) 重启NetBeans

设置NetBeans默认编码UTF-8。

您的netbeans_default_options可能在引号内包含其他参数。在这种情况下,添加-J-Dfile。encoding=UTF-8在字符串的末尾。用空格将其与其他参数分隔开。

例子:

netbeans_default_options="-J-client -J-Xss128m -J-Xms256m . -J-Dapple.laf -J-XX: PermSize = 32米。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"));