java.io.ByteArrayOutputStream.toString java code examples

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

return result.toString("UTF-8"); HowtousetoStringmethodinjava.io.ByteArrayOutputStreamBestJavacodesnippetsusingjava.io.ByteArrayOutputStream.toString(Showingtop20resultsoutof24,237)RefinesearchByteArrayOutputStream.PrintStream.ByteArrayOutputStream.writeTest.PrintStream.printlnInputStream.readAssert.assertEqualsByteArrayOutputStreamresult=newByteArrayOutputStream(); byte[]buffer=newbyte[1024]; intlength; while((length=inputStream.read(buffer))!=-1){ result.write(buffer,0,length); } returnresult.toString("UTF-8"); @Override publicStringconvert(Propertiessource){ try{ ByteArrayOutputStreamos=newByteArrayOutputStream(256); source.store(os,null); returnos.toString("ISO-8859-1"); } catch(IOExceptionex){ //Shouldneverhappen. thrownewIllegalArgumentException("Failedtostore["+source+"]intoString",ex); } } publicstaticStringtoString(InputStreaminputStream)throwsIOException{ ByteArrayOutputStreamresult=newByteArrayOutputStream(); byte[]buffer=newbyte[1024]; intlength; while((length=inputStream.read(buffer))!=-1){ result.write(buffer,0,length); } returnresult.toString("UTF-8"); } voidassertClosed() { if(!c.isClosed()) { ByteArrayOutputStreamout=newByteArrayOutputStream(); PrintStreamprintStream=newPrintStream(out); for(StackTraceElementtraceElement:stackTrace) { printStream.println("\tat"+traceElement); } printStream.println(); thrownewIllegalStateException(format("Closeable%swasnotclosed!\n%s",c,out.toString())); } } } @Test publicvoidshouldSerializeResponseWithNoCommitUriResultsOrErrors()throwsException { //given ByteArrayOutputStreamoutput=newByteArrayOutputStream(); ExecutionResultSerializerserializer=getSerializerWith(output); //when serializer.finish(); //then Stringresult=output.toString(UTF_8.name()); assertEquals("{\"results\":[],\"errors\":[]}",result); } @Test publicvoidtestReadOneByte()throwsException{ assertEquals('a',tee.read()); assertEquals("a",newString(output.toString(ASCII))); } @Override publicvoidpostEvent(Tevent) { try{ ByteArrayOutputStreambuffer=newByteArrayOutputStream(); JsonGeneratorgenerator=factory.createGenerator(buffer,JsonEncoding.UTF8); serializer.serialize(event,generator); out.println(buffer.toString().trim()); } catch(IOExceptione){ thrownewUncheckedIOException(e); } } } @Test publicvoidtestReadNothing()throwsException{ assertEquals("",newString(output.toString(ASCII))); } /** *ReturnsthestringvalueofthestacktraceforthegivenThrowable. */ publicstaticStringgetStackTraceString(Throwablet){ ByteArrayOutputStreambs=newByteArrayOutputStream(); t.printStackTrace(newPrintStream(bs)); returnbs.toString(); } @Override publicvoidevaluate()throwsThrowable{ System.out.println("2048"); Assert.assertEquals("2048\n",OUTPUT.toString()); OUTPUT.reset(); System.out.println("1234"); Assert.assertEquals("1234\n",OUTPUT.toString()); } }; privatevoiddoFizzBuzz(finalintn,finalStrings)throwsIOException{ finalByteArrayOutputStreambaos=newByteArrayOutputStream(); finalBufferedOutputStreambos=newBufferedOutputStream(baos); System.setOut(newPrintStream(bos)); this.fb.fizzBuzz(n); System.out.flush(); StringplatformDependentExpectedResult=s.replaceAll("\\n",System.getProperty("line.separator")); assertEquals(platformDependentExpectedResult,baos.toString()); } @Test publicvoidtestOldBare()throwsInterruptedException,IOException{ record(); cli.dispatch(newString[]{"-ha"}); assertWaitUntil(()->error.toString().contains("Aquorumhasbeenobtained.")); stop(); assertThat(error.toString()) .contains("Startingclustering...") .contains("Nocluster-hostspecified") .contains("AnydeploymentIDswaitingonaquorumwillnowbedeployed"); } @Test publicvoidshouldSupportEmptyPipelineGroup()throwsException{ PipelineConfigsgroup=newBasicPipelineConfigs("defaultGroup",newAuthorization()); CruiseConfigconfig=newBasicCruiseConfig(group); ByteArrayOutputStreamstream=newByteArrayOutputStream(); newMagicalGoConfigXmlWriter(configCache,ConfigElementImplementationRegistryMother.withNoPlugins()).write(config,stream,true); GoConfigHolderconfigHolder=newMagicalGoConfigXmlLoader(newConfigCache(),ConfigElementImplementationRegistryMother.withNoPlugins()) .loadConfigHolder(stream.toString()); assertThat(configHolder.config.findGroup("defaultGroup"),is(group)); } privateProcessRunner.ProcessResultwriteException(finalByteArrayOutputStreambaos,finalExceptionex){ try{ baos.write(errPrefix.getBytes()); } catch(IOExceptionignore){ } ex.printStackTrace(newPrintStream(baos)); returnnewProcessRunner.ProcessResult(-1,baos.toString()); } } //Createastreamtoholdtheoutput ByteArrayOutputStreambaos=newByteArrayOutputStream(); PrintStreamps=newPrintStream(baos); //IMPORTANT:SavetheoldSystem.out! PrintStreamold=System.out; //TellJavatouseyourspecialstream System.setOut(ps); //Printsomeoutput:goestoyourspecialstream System.out.println("Foofoofoo!"); //Putthingsback System.out.flush(); System.setOut(old); //Showwhathappened System.out.println("Here:"+baos.toString()); publicstaticStringbytyToString(InputStreamin)throwsIOException{ ByteArrayOutputStreamout=newByteArrayOutputStream(); byte[]buf=newbyte[1024]; intnum=0; while((num=in.read(buf))!=-1){ out.write(buf,0,buf.length); } Stringresult=out.toString(); out.close(); returnresult; } } @Test publicvoidshouldSerializeResponseWithCommitUriOnly()throwsException { //given ByteArrayOutputStreamoutput=newByteArrayOutputStream(); ExecutionResultSerializerserializer=getSerializerWith(output); //when serializer.transactionCommitUri(URI.create("commit/uri/1")); serializer.finish(); //then Stringresult=output.toString(UTF_8.name()); assertEquals("{\"commit\":\"commit/uri/1\",\"results\":[],\"errors\":[]}",result); } @Test publicvoidtestReadToArray()throwsException{ finalbyte[]buffer=newbyte[8]; assertEquals(3,tee.read(buffer)); assertEquals('a',buffer[0]); assertEquals('b',buffer[1]); assertEquals('c',buffer[2]); assertEquals(-1,tee.read(buffer)); assertEquals("abc",newString(output.toString(ASCII))); } publicstaticvoidmain(String[]args)throwsException{ //KylinConfig.setSandboxEnvIfPossible(); KylinConfigconfig=KylinConfig.getInstanceFromEnv(); DataModelDesckylinModel=generateKylinModelForMetricsQuery("ADMIN",config,newHiveSinkTool()); ByteArrayOutputStreambuf=newByteArrayOutputStream(); DataOutputStreamdout=newDataOutputStream(buf); MODELDESC_SERIALIZER.serialize(kylinModel,dout); dout.close(); buf.close(); System.out.println(buf.toString("UTF-8")); } @Test publicvoidcanFormatEmptyObject() { json.assemble(newMappingRepresentation("empty") { @Override protectedvoidserialize(MappingSerializerserializer) { } }); assertEquals(JsonHelper.createJsonFrom(Collections.emptyMap()),stream.toString()); } java.ioByteArrayOutputStreamtoStringJavadocReturnsthecontentsofthisByteArrayOutputStreamasastring.Any changesmadetothereceiverafterreturningwillnotbereflectedinthe stringreturnedtothecaller. PopularmethodsofByteArrayOutputStreamConstructsanewByteArrayOutputStreamwithadefaultsizeofsizebytes.If morethansizebytesartoByteArrayReturnsthecontentsofthisByteArrayOutputStreamasabytearray.Anychanges madetothereceiverwriteWritescountbytesfromthebytearraybufferstartingatoffsetindextothis stream.closeClosesthisstream.Thisreleasessystemresourcesusedforthisstream.sizeReturnsthetotalnumberofbyteswrittentothisstreamsofar.resetResetsthisstreamtothebeginningoftheunderlyingbytearray.Allsubsequent writeswilloverwriflushwriteToTakesthecontentsofthisstreamandwritesittotheoutputstreamout.expandensureCapacityIncreasesthecapacityifnecessarytoensurethatitcanholdatleastthe numberofelementsspecigrowIncreasesthecapacitytoensurethatitcanholdatleastthenumberof elementsspecifiedbythemcheckOffsetAndCountgrow,checkOffsetAndCount,copyOfPopularinJavaReadingfromdatabaseusingSQLpreparedstatementscheduleAtFixedRate(ScheduledExecutorService)getOriginalFilename(MultipartFile)Returntheoriginalfilenameintheclient'sfilesystem.Thismaycontainpath informationdependingonCreateOptionsMenu(Activity)Graphics2D(java.awt)ThisGraphics2DclassextendstheGraphicsclasstoprovidemoresophisticated controlovergraphicsTimerTask(java.util)TheTimerTaskclassrepresentsatasktorunataspecifiedtime.Thetaskmay berunonceorrepeatExecutor(java.util.concurrent)AnobjectthatexecutessubmittedRunnabletasks.Thisinterfaceprovidesaway ofdecouplingtasksJPanel(javax.swing)Reflections(org.reflections)Reflectionsone-stop-shopobjectReflectionsscansyourclasspath,indexesthe metadata,allowsyoutOption(scala)ToppluginsforAndroidStudioProductsSearchforJavacodeSearchforJavaScriptcodeIDEPluginsIntelliJIDEAWebStormVisualStudioAndroidStudioEclipseVisualStudioCodePyCharmSublimeTextPhpStormVimGoLandRubyMineEmacsJupyterNotebookJupyterLabRiderDataGripAppCodeCompanyAboutUsContactUsCareersResourcesFAQBlogTabnineAcademyTermsofusePrivacypolicyJavaCodeIndexJavascriptCodeIndexGetTabnineforyourIDEnow



請為這篇文章評分?