Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal Character when trying to compile java code

Tags:

java

javac

I have a program that allows a user to type java code into a rich text box and then compile it using the java compiler. Whenever I try to compile the code that I have written I get an error that says that I have an illegal character at the beginning of my code that is not there. This is the error the compiler is giving me:

C:\Users\Travis Michael>"\Program Files\Java\jdk1.6.0_17\bin\javac" Test.java Test.java:1: illegal character: \187 public class Test  ^ Test.java:1: illegal character: \191 public class Test   ^ 2 errors 
like image 461
muckdog12 Avatar asked Jan 02 '10 21:01

muckdog12


1 Answers

The BOM is generated by, say, File.WriteAllText() or StreamWriter when you don't specify an Encoding. The default is to use the UTF8 encoding and generate a BOM. You can tell the java compiler about this with its -encoding command line option.

The path of least resistance is to avoid generating the BOM. Do so by specifying System.Text.Encoding.Default, that will write the file with the characters in the default code page of your operating system and doesn't write a BOM. Use the File.WriteAllText(String, String, Encoding) overload or the StreamWriter(String, Boolean, Encoding) constructor.

Just make sure that the file you create doesn't get compiled by a machine in another corner of the world. It will produce mojibake.

like image 164
Hans Passant Avatar answered Sep 25 '22 14:09

Hans Passant