Illegal Character Compilation Error | Baeldung
文章推薦指數: 80 %
The illegal character compilation error is a file type encoding error. It's produced if we use an incorrect encoding in our files when they ...
StartHereCourses ▼▲
RESTwithSpring
ThecanonicalreferenceforbuildingaproductiongradeAPIwithSpring
LearnSpringSecurity ▼▲
THEuniqueSpringSecurityeducationifyou’reworkingwithJavatoday
LearnSpringSecurityCore
FocusontheCoreofSpringSecurity5
LearnSpringSecurityOAuth
FocusonthenewOAuth2stackinSpringSecurity5
LearnSpring
Fromnoexperiencetoactuallybuildingstuff
LearnSpringDataJPA
ThefullguidetopersistencewithSpringDataJPA
Guides ▼▲
Persistence
ThePersistencewithSpringguides
REST
TheguidesonbuildingRESTAPIswithSpring
Security
TheSpringSecurityguides
About ▼▲
FullArchive
Thehighleveloverviewofallthearticlesonthesite.
BaeldungEbooks
DiscoverallofoureBooks
WriteforBaeldung
Becomeawriteronthesite
AboutBaeldung
AboutBaeldung.
JavaTop
GetstartedwithSpring5andSpringBoot2,throughtheLearnSpringcourse:
>CHECKOUTTHECOURSE
1.Overview
Theillegalcharactercompilationerrorisafiletypeencodingerror.It'sproducedifweuseanincorrectencodinginourfileswhentheyarecreated.Asresult,inlanguageslikeJava,wecangetthistypeoferrorwhenwetrytocompileourproject.Inthistutorial,we'lldescribetheproblemindetailalongwithsomescenarioswherewemayencounterit,andthen,we'llpresentsomeexamplesofhowtoresolveit.
2.IllegalCharacterCompilationError
2.1.ByteOrderMark(BOM)
Beforewegointothebyteordermark,weneedtotakeaquicklookattheUCS(Unicode)TransformationFormat(UTF).UTFisacharacterencodingformatthatcanencodeallofthepossiblecharactercodepointsinUnicode.ThereareseveralkindsofUTFencodings.Amongallthese,UTF-8hasbeenthemostused.
UTF-8usesan8-bitvariable-widthencodingtomaximizecompatibilitywithASCII.Whenweusethisencodinginourfiles,wemayfindsomebytesthatrepresenttheUnicodecodepoint.Asaresult,ourfilesstartwithaU+FEFFbyteordermark(BOM).Thismark,correctlyused,isinvisible.However,insomecases,itcouldleadtodataerrors.
IntheUTF-8encoding,thepresenceoftheBOMisnotfundamental.Althoughit'snotessential,theBOMmaystillappearinUTF-8encodedtext.TheBOMadditioncouldhappeneitherbyanencodingconversionorbyatexteditorthatflagsthecontentasUTF-8.
TexteditorslikeNotepadonWindowscouldproducethiskindofaddition.Asaconsequence,whenweuseaNotepad-liketexteditortocreateacodeexampleandtrytorunit,wecouldgetacompilationerror.Incontrast,modernIDEsencodecreatedfilesasUTF-8withouttheBOM.Thenextsectionswillshowsomeexamplesofthisproblem.
2.2.ClasswithIllegalCharacterCompilationError
Typically,weworkwithadvancedIDEs,butsometimes,weuseatexteditorinstead.Unfortunately,aswe'velearned,sometexteditorscouldcreatemoreproblemsthansolutionsbecausesavingafilewithaBOMcouldleadtoacompilationerrorinJava.The“illegalcharacter”erroroccursinthecompilationphase,soit'squiteeasytodetect.Thenextexampleshowsushowitworks.
First,let'swriteasimpleclassinourtexteditor,suchasNotepad.Thisclassisjustarepresentation–wecouldwriteanycodetotest.Next,wesaveourfilewiththeBOMtotest:
publicclassTestBOM{
publicstaticvoidmain(String...args){
System.out.println("BOMTest");
}
}
Now,whenwetrytocompilethisfileusingthejavaccommand:
$javac./TestBOM.java
Consequently,wegettheerrormessage:
publicclassTestBOM{
^
.\TestBOM.java:1:error:illegalcharacter:'\u00bf'
publicclassTestBOM{
^
2errors
Ideally,tofixthisproblem,theonlythingtodoissavethefileasUTF-8withoutBOMencoding.Afterthat,theproblemissolved.WeshouldalwayscheckthatourfilesaresavedwithoutaBOM.
Anotherwaytofixthisissueiswithatoollikedos2unix.ThistoolwillremovetheBOMandalsotakecareofotheridiosyncrasiesofWindowstextfiles.
3.ReadingFiles
Additionally,let'sanalyzesomeexamplesofreadingfilesencodedwithBOM.
Initially,weneedtocreateafilewithBOMtouseforourtest.Thisfilecontainsoursampletext,“HelloworldwithBOM.”–whichwillbeourexpectedstring.Next,let'sstarttesting.
3.1.ReadingFilesUsingBufferedReader
First,we'lltestthefileusingtheBufferedReaderclass:
@Test
publicvoidwhenInputFileHasBOM_thenUseInputStream()throwsIOException{
Stringline;
Stringactual="";
try(BufferedReaderbr=newBufferedReader(newInputStreamReader(file))){
while((line=br.readLine())!=null){
actual+=line;
}
}
assertEquals(expected,actual);
}
Inthiscase,whenwetrytoassertthatthestringsareequal,wegetanerror:
org.opentest4j.AssertionFailedError:expected:
延伸文章資訊
- 1Error: (1, 1) java: Illegal character:'\ufeff' [How to Solve]
When opening the eclipse java project compiling with IDEA, the following error occurred: Error:(1...
- 2error: illegal character: '\ufeff' in java - Stack Overflow
As Jim Garrison pointed out, you probably have a Byte Order Marker (BOM) at the start of the file...
- 3Linux下Java编译错误:illegal character: '\ufeff' - 简书
Linux下Java编译错误:illegal character: '\ufeff'. Everlin 关注. 2017.11.18 19:36:58 字数401阅读2,324. 同事在Jenk...
- 4anruy - 博客园
转-java编译时error: illegal character '\ufeff' 的解决 ... 查看了该xxx.java类的属性,才发现玄机所在: 编译有问题的文件属性:(注意最下面 ...
- 5Error:(1, 1) java: 非法字元: '/ufeff' - 程式人生