0

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?

5
  • Does this answer your question? Setting the default Java character encoding Commented Dec 4, 2019 at 18:29
  • No, I want to change the default charset from within the code Commented Dec 4, 2019 at 18:39
  • Unfortunately, the file.encoding property has to be specified as the JVM starts up It is in the answer Commented Dec 4, 2019 at 18:57
  • is there anyway that i take user input in bytes and convert into string with utf-8 format? Commented Dec 4, 2019 at 19:19
  • 1
    There 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. Commented Dec 4, 2019 at 21:25

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.