How to compile a java source file which is encoded as "UTF-8"?

asela38 picture asela38 · Nov 13, 2009 · Viewed 70.4k times · Source

I saved my Java source file specifying it's encoding type as UTF-8 (using Notepad, by default Notepad's encoding type is ANSI) and then I tried to compile it using:

javac -encoding "UTF-8" One.java

but it gave an error message"

One.java:1: illegal character: \65279

?public class One {

^
1 error

Is there any other way, I can compile this?

Here is the source:

public class One {
    public static void main( String[] args ){
        System.out.println("HI");
    }
} 

Answer

Daniel Pryden picture Daniel Pryden · Nov 13, 2009

Your file is being read as UTF-8, otherwise a character with value "65279" could never appear. javac expects your source code to be in the platform default encoding, according to the javac documentation:

If -encoding is not specified, the platform default converter is used.

Decimal 65279 is hex FEFF, which is the Unicode Byte Order Mark (BOM). It's unnecessary in UTF-8, because UTF-8 is always encoded as an octet stream and doesn't have endianness issues.

Notepad likes to stick in BOMs even when they're not necessary, but some programs don't like finding them. As others have pointed out, Notepad is not a very good text editor. Switching to a different text editor will almost certainly solve your problem.