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:
延伸文章資訊
- 1Illegal Character Compilation Error | Baeldung
The illegal character compilation error is a file type encoding error. It's produced if we use an...
- 2Byte Order Mark in java file – IDEs Support (IntelliJ Platform)
Error:(1, 1) java: illegal character: '\ufeff' Error:(1, 10) java: class, interface, or enum expe...
- 3java编译时error: illegal character '\ufeff' 的解决办法 - 程序员秘密
java编译时error: illegal character '\ufeff' 的解决办法_t518vs20s的博客-程序员秘密. 技术标签: java. 原文链接:https://blog....
- 4Linux下Java编译错误:illegal character: '\ufeff' - 简书
Linux下Java编译错误:illegal character: '\ufeff'. Everlin 关注. 2017.11.18 19:36:58 字数401阅读2,324. 同事在Jenk...
- 5Error:(1, 1) java: 非法字元: '/ufeff' - 程式人生