Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify the encoding of Java source files?

I use weird Unicode strings in my Java test cases. The compiler seemingly interprets the file as iso-8859-1, causing JUnit to complain.

In Python I can specify the encoding at the top of the file:

# -*- coding: utf-8 -*-

Is there an equivalent in Java? How can I detect / specify the encoding of .java files?

like image 440
Frederik Avatar asked Feb 12 '12 10:02

Frederik


People also ask

Is Java UTF-8 or 16?

The native character encoding of the Java programming language is UTF-16. A charset in the Java platform therefore defines a mapping between sequences of sixteen-bit UTF-16 code units (that is, sequences of chars) and sequences of bytes.

How do I save a Java file as UTF-8?

In Java, the OutputStreamWriter accepts a charset to encode the character streams into byte streams. We can pass a StandardCharsets. UTF_8 into the OutputStreamWriter constructor to write data to a UTF-8 file.

What is source file encoding?

Scheme source code files are usually encoded in ASCII or UTF-8, but the built-in reader can interpret other character encodings as well. When Guile loads Scheme source code, it uses the file-encoding procedure (described below) to try to guess the encoding of the file. In the absence of any hints, UTF-8 is assumed.


2 Answers

You can set it when you compile the file with the parameter "-encoding"

http://docs.oracle.com/javase/6/docs/technotes/tools/windows/javac.html

like image 90
Figus Avatar answered Oct 24 '22 21:10

Figus


The javac compiler has a parameter -encoding where you can set it. In Eclipse you must change the project settings or the global settings for *.java files.

like image 39
A.H. Avatar answered Oct 24 '22 22:10

A.H.