Encode String in UTF-8 in Java | Delft Stack
文章推薦指數: 80 %
Encode String in UTF-8 in Java · Encode a String to UTF-8 by Converting It to Bytes Array and Using new String() · Encode a String to UTF-8 Using ... JavaHowtosPerformStringtoStringArrayConversioninJavaRemoveSubstringFromStringinJavaSortObjectsinArrayListbyDateinJavaConcatenateTwoArraysinJavaConvertByteArrayinHexStringinJavaConvertJavaStringIntoByteAddOneDaytoaDateinJavaCompareTwoDatesinJavareportthisad reportthisadHowToJavaHowtosEncodeStringinUTF-8inJavaEncodeaStringtoUTF-8byConvertingIttoBytesArrayandUsingnewString()EncodeaStringtoUTF-8UsingStandardCharsets.UTF_8.encodeandStandardCharsets.UTF_8.decode(byteBuffer)EncodeStringsFromaFiletoUTF-8UsingFiles.readString()WeneedtousetheconceptofencodinganddecodingwhenweworkwithStrings,andwewanttoconvertthatstringtoanothercharacterset.UTF-8,whichisshortforUnicodeTransformationFormat-8bit,isavariable-widthstandardthatassignsadifferentnumberofbytesfromonetofourtoeverycodepointorcharacter.Belowwecheckouthowtoencodeastringandafile’scontentstoUTF-8standard.EncodeaStringtoUTF-8byConvertingIttoBytesArrayandUsingnewString()WefirstconvertthestringtoanarrayofbytesinthefirstmethodandcreateastringwiththeUTF-8encoding.WecreateastringjapaneseStringthatcontainsJapanesecharacters.Next,weconvertthestringtoabytearraybecausewecannotencodeastringdirectlytoUTF-8.japaneseString.getBytes()returnsanarrayofbytetype.NowwecreateanewStringusingnewString()andpassintwoarguments,thefirstargumentisthebytearrayjapaneseBytesArray,andthesecondargumentistheencodingformatthatwewanttouse.WeusetheStandardCharsetsclasstogettheencodingcharsetandaccesstheUTH_8field.TheencodedStringcontainsastringthatisencodedwithUTF-8.importjava.nio.charset.StandardCharsets; publicclassJavaExample{ publicstaticvoidmain(String[]args){ StringjapaneseString="これはテキストです"; byte[]japaneseBytesArray=japaneseString.getBytes(); StringencodedString=newString(japaneseBytesArray,StandardCharsets.UTF_8); System.out.println(encodedString); } } Output:これはテキストです EncodeaStringtoUTF-8UsingStandardCharsets.UTF_8.encodeandStandardCharsets.UTF_8.decode(byteBuffer)WecanusetheStandardCharsetsclasstoencodeastringtospecifiedcharsetlikeUTF-8.WecreateajapaneseStringandthencallencode()ofStandardCharsets.UTF_8thatisoftypecharsets.Intheencode()method,wepassthejapaneseString,returningaByteBufferobject.ThestringiscurrentlyintheformofaByteBuffer,sowecallthedecode()methodofStandardCharsets.UTF_8thattakestheByteBufferobjectasanargument,andatlast,weconverttheresulttoastringusingtoString().importjava.nio.ByteBuffer; importjava.nio.charset.StandardCharsets; publicclassJavaExample{ publicstaticvoidmain(String[]args){ StringjapaneseString="これはテキストです"; ByteBufferbyteBuffer=StandardCharsets.UTF_8.encode(japaneseString); StringencodedString=StandardCharsets.UTF_8.decode(byteBuffer).toString(); System.out.println(encodedString); } } Output:これはテキストです EncodeStringsFromaFiletoUTF-8UsingFiles.readString()IntheLastexample,insteadofencodingasinglestringtoUTF-8format,wereadafileandencodeallthestringsinthefile.First,wecreateatextfileandaddsometexttoencodeintheUTF-8standard.Togetthefile’spath,weusePaths.get()andpassinthefile’spathasanargumentthatreturnsaPathobject.WecallthereadString()methodoftheFilesclassthattakestwoarguments,thefirstargumentisthePathobject,andthesecondargumentisthecharsettousethatweaccessusingStandardCharsets.UTF_8.WegettheencodedstringreadStringandprintitintheoutput.importjava.io.IOException; importjava.nio.charset.StandardCharsets; importjava.nio.file.Files; importjava.nio.file.Path; importjava.nio.file.Paths; publicclassJavaExample{ publicstaticvoidmain(String[]args){ try{ Pathpath=Paths.get("C:\\Users\\User1\\IdeaProjects\\JavaExamples\\src\\main\\java\\example_file.txt"); StringreadString=Files.readString(path,StandardCharsets.UTF_8); System.out.println(readString); }catch(IOExceptione){ e.printStackTrace(); } } } Output:これはテキストです Tämäontekstiä RelatedArticle-JavaStringPerformStringtoStringArrayConversioninJavaRemoveSubstringFromStringinJavaConvertByteArrayinHexStringinJavaConvertJavaStringIntoByteCheckifStringContainsNumbersinJavaOperatorOverloadinginJavax
延伸文章資訊
- 1Java String Encoding - Javatpoint
In Java, when we deal with String sometimes it is required to encode a string in a specific chara...
- 2Byte Encodings and Strings (The Java™ Tutorials ...
Byte Encodings and Strings ... If a byte array contains non-Unicode text, you can convert the tex...
- 3Encode String to UTF-8 - java - Stack Overflow
A Java String is internally always encoded in UTF-16 - but you really should think about it like ...
- 4java中string类型转换成UTF-8 - CSDN博客
1、测试方法如下: public static String toUtf8(String str) { return new String(str.getBytes("UTF-8"),"UTF-...
- 5Java String - Jenkov.com