Convert String to UTF-8 bytes in Java - Tutorialspoint

文章推薦指數: 80 %
投票人數:10人

UTF-8 is a variable width character encoding. UTF-8 has ability to be as condense as ASCII but can also contain any unicode characters with some ... Home CodingGround Jobs Whiteboard Tools Business Teachwithus TrendingCategories DataStructure Networking RDBMS OperatingSystem Java iOS HTML CSS Android Python CProgramming C++ C# MongoDB MySQL Javascript PHP SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho ConvertStringtoUTF-8bytesinJava Java8ObjectOrientedProgrammingProgramming CompleteJavaProgrammingFundamentalsWithSampleProjects 98Lectures 7.5hours EmenwaGlobal,EjikeIfeanyiChukwu MoreDetail GetyourJavadreamjob!Beginnersinterviewpreparation 85Lectures 6hours YuvalIshay MoreDetail CoreJavabootcampprogramwithHandsonpractice Featured 99Lectures 17hours PrashantMishra MoreDetail BeforeconvertingaStringtoUTF-8-bytes,letushavealookatUTF-8.UTF-8isavariablewidthcharacterencoding.UTF-8hasabilitytobeascondenseasASCIIbutcanalsocontainanyunicodecharacterswithsomeincreaseinthesizeofthefile.UTFstandsforUnicodeTransformationFormat.The'8'signifiesthatitallocates8-bitblockstodenoteacharacter.Thenumberofblocksneededtorepresentacharactervariesfrom1to4.InordertoconvertaStringintoUTF-8,weusethegetBytes()methodinJava.ThegetBytes()methodencodesaStringintoasequenceofbytesandreturnsabytearray.Declaration−ThegetBytes()methodisdeclaredasfollows−publicbyte[]getBytes(StringcharsetName)wherecharsetNameisthespecificcharsetbywhichtheStringisencodedintoanarrayofbytes.LetusseeaprogramtoconvertaStringintoUTF-8bytesinJava.Example LiveDemopublicclassExample{   publicstaticvoidmain(Stringargs[])throwsException{    Strings="HelloWorld";    bytearr[]=s.getBytes("UTF8");    for(bytex:arr){      System.out.print(x+"");    }   } }Output721011081081113287111114108100Letusunderstandtheaboveprogram.WehavecreatedaStrings−Strings="HelloWorld";StringsisassignedthevalueHelloWorld.ToconvertitintoUTF-8,weusethegetBytes(“UTF-8”)method.Thisgivesusanarrayofbytesasfollows−byte[]arr=s.getBytes("UTF-8");Thentoprintthebytearray,weuseanenhancedforloopasfollows−for(bytex:arr){   System.out.print(x+""); } AnviJain Updatedon26-Jun-202013:45:42 RelatedQuestions&AnswersConvertUnicodetoUTF-8inJava ConvertUTF-8toUnicodeinJava ConvertASCIITOUTF-8EncodinginPHP? Convertbytestoastringinjava HowtoconvertwronglyencodeddatatoUTF-8inMySQL? UTF-8ValidationinC++ HowtoconvertanMySQLdatabasecharactersetandcollationtoUTF-8? HowtoconvertDatetoStringinJava8? HowmanybitsareusedtorepresentUnicode,ASCII,UTF-16,andUTF-8charactersinjava? HowcanIconvertbytestoaPythonstring? HowwouldyouconvertstringtobytesinPython3? ChangeMySQLdefaultcharactersettoUTF-8inmy.cnf? Howtoreadandwriteunicode(UTF-8)filesinPython? HowcanTensorflowtextbeusedtosplittheUTF-8stringsinPython? HowtoConvertaJava8StreamtoanArray? PreviousPage PrintPage NextPage  Advertisements



請為這篇文章評分?