How to convert a String to and fro from UTF8 byte array

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

Following example will showcase conversion of a Unicode String to UTF8 byte[] and UTF8 byte[] to Unicode byte[] using Reader and Writer ... 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 HowtoconvertaStringtoandfrofromUTF8bytearray Java8ObjectOrientedProgrammingProgramming CompleteJavaProgrammingFundamentalsWithSampleProjects 98Lectures 7.5hours EmenwaGlobal,EjikeIfeanyiChukwu MoreDetail GetyourJavadreamjob!Beginnersinterviewpreparation 85Lectures 6hours YuvalIshay MoreDetail CoreJavabootcampprogramwithHandsonpractice Featured 99Lectures 17hours PrashantMishra MoreDetail FollowingexamplewillshowcaseconversionofaUnicodeStringtoUTF8byte[]andUTF8byte[]toUnicodebyte[]usingReaderandWriterclasses.ExampleIOTester.javaimportjava.io.ByteArrayInputStream; importjava.io.ByteArrayOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.InputStreamReader; importjava.io.OutputStreamWriter; importjava.io.Reader; importjava.io.Writer; importjava.nio.charset.Charset; importjava.text.ParseException; publicclassI18NTester{   publicstaticvoidmain(String[]args)throwsParseException,IOException{   Stringinput="Thisisasampletext";   InputStreaminputStream=newByteArrayInputStream(input.getBytes());   //gettheUTF-8dataReader   reader=newInputStreamReader(inputStream,Charset.forName("UTF-8"));      //convertUTF-8toUnicode   intdata=reader.read();   while(data!=-1){    chartheChar=(char)data;    System.out.print(theChar);    data=reader.read();   }reader.close();   System.out.println();   //ConvertUnicodetoUTF-8Bytes   ByteArrayOutputStreamoutputStream=newByteArrayOutputStream();   Writerwriter=newOutputStreamWriter(outputStream,Charset.forName("UTF-8"));   writer.write(input);writer.close();   Stringout=newString(outputStream.toByteArray());   System.out.println(out);} }OutputItwillprintthefollowingresult. ThisisasampletextThisisasampletext AmitSharma Updatedon24-Feb-202010:36:31 RelatedQuestions&AnswersHowtoconvertbytearraytostringinC#? HowtoconvertabytearraytohexstringinJava? JavaProgramtoconvertbyte[]arraytoString JavaProgramtoconvertStringtobytearray HowtoconvertabytearraytoahexstringinJava? HowtoconverthexstringtobyteArrayinJava? ConvertbyteArraytoHexStringinJava ConvertHexStringtobyteArrayinJava ConvertbytetoStringinJava HowtoconvertaPDFtobytearrayinJava? JavaProgramtocreateStreamfromaString/ByteArray JavaProgramtoconvertbytetostring JavaProgramtoconvertstringtobyte ConvertaStringtoabytenumberinJava HowtoconvertBLOBtoByteArrayinjava? PreviousPage PrintPage NextPage  Advertisements



請為這篇文章評分?