尝试编译 Java 代码时出现非法字符 [英] Illegal Character when trying to compile java code

查看:33
本文介绍了尝试编译 Java 代码时出现非法字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,它允许用户在富文本框中键入 java 代码,然后使用 java 编译器对其进行编译.每当我尝试编译我编写的代码时,都会收到一条错误消息,指出我的代码开头有一个不存在的非法字符.这是编译器给我的错误:

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:UsersTravis Michael>"Program FilesJavajdk1.6.0_17injavac" Test.java
Test.java:1: illegal character: 187
public class Test
 ^
Test.java:1: illegal character: 191
public class Test
  ^
2 errors

推荐答案

当您未指定 Encoding 时,BOM 是由 File.WriteAllText() 或 StreamWriter 生成的.默认使用 UTF8 编码并生成 BOM.你可以用它的 -encoding 命令行选项告诉 java 编译器这个.

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.

阻力最小的路径是避免生成 BOM.通过指定 System.Text.Encoding.Default 执行此操作,这将使用操作系统默认代码页中的字符写入文件,而不写入 BOM.使用 File.WriteAllText(String, String, Encoding) 重载或 StreamWriter(String, Boolean, Encoding) 构造函数.

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.

只要确保您创建的文件不会被世界另一个角落的机器编译即可.它将产生 mojibake.

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.

这篇关于尝试编译 Java 代码时出现非法字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆