When defining the below string on Java JDK 9 String s = "एक गाव में एक किसान" It throws the following error: Unmappable character (0xE0) for encoding US-ASCII I understand that it is UTF-8 encoded but as JDK 9 has default charset set as US-ASCII but I can't find how to change the default charset to UTF-8 from the code itself?
Asked
Active
Viewed 131 times
0
-
Does this answer your question? [Setting the default Java character encoding](https://stackoverflow.com/questions/361975/setting-the-default-java-character-encoding) – Gatusko Dec 04 '19 at 18:29
-
No, I want to change the default charset from within the code – A.Raw Dec 04 '19 at 18:39
-
`Unfortunately, the file.encoding property has to be specified as the JVM starts up` It is in the answer – Gatusko Dec 04 '19 at 18:57
-
is there anyway that i take user input in bytes and convert into string with utf-8 format? – A.Raw Dec 04 '19 at 19:19
-
1There are 2 different issues: encoding of sources and encoding for IO operations in your code. When you have written some .java files in non-default encoding,you have to say java compiler what encoding it should use to read the sources to parse them correctly. The second issue is how you read/write data in your code. It also uses default encoding, but there is a lot of specific methods to read/write data using encoding explicitly like: InputStreamReader(InputStream in,String charsetName), OutputStreamWriter(OutputStream out,String charsetName), String(byte[] bytes, String charsetName)etc. – AnatolyG Dec 04 '19 at 21:25
1 Answers
2
I want to change the default charset from within the code
Impossible1.
The source code is just text, it doesn't define the encoding used to store that text.
You can however decide that your source code is US-ASCII, so the encoding doesn't matter (excl. UTF-16, UTF-32, etc), by specifying all non-ASCII characters as Unicode escapes:
String s = "\u090f\u0915 \u0917\u093e\u0935 \u092e\u0947\u0902 \u090f\u0915 \u0915\u093f\u0938\u093e\u0928"
Of course, it makes it difficult to know what the string says.
1) Since Java doesn't support BOM's.

Andreas
- 154,647
- 11
- 152
- 247