我有一个“ñ”字符的字符串,我有一些问题。我需要将这个字符串编码为UTF-8编码。我试过这种方法,但行不通:
byte ptext[] = myString.getBytes();
String value = new String(ptext, "UTF-8");
如何将该字符串编码为utf-8?
我有一个“ñ”字符的字符串,我有一些问题。我需要将这个字符串编码为UTF-8编码。我试过这种方法,但行不通:
byte ptext[] = myString.getBytes();
String value = new String(ptext, "UTF-8");
如何将该字符串编码为utf-8?
当前回答
我已经使用下面的代码编码特殊字符通过指定编码格式。
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");
其他回答
这解决了我的问题
String inputText = "some text with escaped chars"
InputStream is = new ByteArrayInputStream(inputText.getBytes("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) {
//...
}
Java String在内部总是用UTF-16编码——但是你真的应该这样想:编码是一种在字符串和字节之间转换的方式。
如果你有编码问题,当你有字符串的时候,就来不及修正了。您需要修复从文件、DB或网络连接中创建字符串的位置。
你可以试试这种方法。
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);