I have a String with a \"ñ\" character and I have some problems with it. I need to encode this String to UTF-8 encoding. I have tried it by this way, but it doesn\'t work:
How about using
ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(myString)
String
objects in Java use the UTF-16 encoding that can't be modified.
The only thing that can have a different encoding is a byte[]
. So if you need UTF-8 data, then you need a byte[]
. If you have a String
that contains unexpected data, then the problem is at some earlier place that incorrectly converted some binary data to a String
(i.e. it was using the wrong encoding).
String value = new String(myString.getBytes("UTF-8"));
and, if you want to read from text file with "ISO-8859-1" encoded:
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) {
//...
}
Use byte[] ptext = String.getBytes("UTF-8");
instead of getBytes()
. getBytes()
uses so-called "default encoding", which may not be UTF-8.
This solved my problem
String inputText = "some text with escaped chars"
InputStream is = new ByteArrayInputStream(inputText.getBytes("UTF-8"));
You can try this way.
byte ptext[] = myString.getBytes("ISO-8859-1");
String value = new String(ptext, "UTF-8");