Java Code Examples of java.io.ByteArrayOutputStream

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

getResourceAsStream("transform-0-1.xslt"); ByteArrayOutputStream os=new ... toByteArray(),"utf-8"); } catch ( IOException e) { throw new ... PopularClasses Sources -Examples -Discussions JavaCodeExamplesforjava.io.ByteArrayOutputStream Thefollowingcodeexamplesareextractedfromopensourceprojects.Youcanclickto voteuptheexamplesthatareusefultoyou. Example1 Fromprojectaddis,underdirectory/application/src/main/java/org/drugis/addis/util/jaxb/. Sourcefile: JAXBConvertor.java   28  /** *ConvertlegacyXML("version0")toschemav1compliantXML. *@paramxmlLegacyXMLinputstream. *@returnSchemav1compliantXML. */ publicstaticInputStreamtransformLegacyXML(InputStreamxml)throwsTransformerException,IOException{ System.setProperty("javax.xml.transform.TransformerFactory","net.sf.saxon.TransformerFactoryImpl"); TransformerFactorytFactory=TransformerFactory.newInstance(); InputStreamxsltFile=JAXBConvertor.class.getResourceAsStream("transform-0-1.xslt"); ByteArrayOutputStreamos=newByteArrayOutputStream(); javax.xml.transform.SourcexmlSource=newjavax.xml.transform.stream.StreamSource(xml); javax.xml.transform.SourcexsltSource=newjavax.xml.transform.stream.StreamSource(xsltFile); javax.xml.transform.Resultresult=newjavax.xml.transform.stream.StreamResult(os); javax.xml.transform.Transformertrans=tFactory.newTransformer(xsltSource); trans.transform(xmlSource,result); os.close(); returnnewByteArrayInputStream(os.toByteArray()); } Example2 Fromprojectagit,underdirectory/agit/src/main/java/com/madgag/agit/diff/. Sourcefile: LineContextDiffer.java   27  privateStringextractHunk(RawTextrawText,intstartLine,intendLine){ try{ ByteArrayOutputStreambas=newByteArrayOutputStream(); for(intline=startLine;line0){ out.write(c); } returnnewString(out.toByteArray(),charset); } Example6 FromprojectAirCastingAndroidClient,underdirectory/src/main/java/pl/llp/aircasting/helper/. Sourcefile: GZIPHelper.java   26  publicbyte[]zippedSession(Sessionsession)throwsIOException{ ByteArrayOutputStreambyteStream=newByteArrayOutputStream(); Base64OutputStreambase64OutputStream=newBase64OutputStream(byteStream); GZIPOutputStreamgzip=newGZIPOutputStream(base64OutputStream); OutputStreamWriterwriter=newOutputStreamWriter(gzip); gson.toJson(session,session.getClass(),writer); writer.flush(); gzip.finish(); writer.close(); returnbyteStream.toByteArray(); } Example7 Fromprojectairlift,underdirectory/event/src/test/java/io/airlift/event/client/. Sourcefile: TestJsonEventSerializer.java   26  @TestpublicvoidtestEventSerializer()throwsException{ JsonEventSerializereventSerializer=newJsonEventSerializer(FixedDummyEventClass.class); ByteArrayOutputStreamout=newByteArrayOutputStream(); JsonGeneratorjsonGenerator=newJsonFactory().createJsonGenerator(out,JsonEncoding.UTF8); FixedDummyEventClassevent=TestingUtils.getEvents().get(0); eventSerializer.serialize(event,jsonGenerator); Stringjson=out.toString(Charsets.UTF_8.name()); assertEquals(json,TestingUtils.getNormalizedJson("event.json")); } Example8 Fromprojectajah,underdirectory/ajah-image/src/main/java/com/ajah/image/. Sourcefile: AutoCrop.java   26  /** *Cropsanimagebasedonthevalueofthetopleftpixel. *@paramdataTheimagedata. *@paramfuzzinessThefuzzinessallowedforminordeviations(~5isrecommended). *@returnThenewimagedata,cropped. *@throwsIOExceptionIftheimagecouldnotberead. */ publicstaticbyte[]autoCrop(finalbyte[]data,finalintfuzziness)throwsIOException{ finalBufferedImageimage=ImageIO.read(newByteArrayInputStream(data)); finalBufferedImagecropped=autoCrop(image,fuzziness); finalByteArrayOutputStreamout=newByteArrayOutputStream(); ImageIO.write(cropped,"png",out); returnout.toByteArray(); } Example9 Fromprojectakela,underdirectory/src/main/java/com/mozilla/hadoop/hbase/mapreduce/. Sourcefile: MultiScanTableMapReduceUtil.java   26  /** *ConvertsanarrayofScanobjectsintoabase64string *@paramscans *@return *@throwsIOException */ publicstaticStringconvertScanArrayToString(finalScan[]scans)throwsIOException{ finalByteArrayOutputStreambaos=newByteArrayOutputStream(); finalDataOutputStreamdos=newDataOutputStream(baos); ArrayWritableaw=newArrayWritable(Scan.class,scans); aw.write(dos); returnBase64.encodeBytes(baos.toByteArray()); } Example10 FromprojectAmDroid,underdirectory/httpclientandroidlib/src/ch/boye/httpclientandroidlib/entity/. Sourcefile: SerializableEntity.java   26  privatevoidcreateBytes(Serializableser)throwsIOException{ ByteArrayOutputStreambaos=newByteArrayOutputStream(); ObjectOutputStreamout=newObjectOutputStream(baos); out.writeObject(ser); out.flush(); this.objSer=baos.toByteArray(); } Example11 Fromprojectamplafi-sworddance,underdirectory/src/test/java/com/sworddance/taskcontrol/. Sourcefile: TestFutureListenerNotifier.java   26  privateFserializeDeserialize(FfutureResult)throwsIOException,ClassNotFoundException{ ByteArrayOutputStreamout=newByteArrayOutputStream(); ObjectOutputStreamobjectOutputStream=newObjectOutputStream(out); objectOutputStream.writeObject(futureResult); objectOutputStream.close(); ByteArrayInputStreamin=newByteArrayInputStream(out.toByteArray()); ObjectInputStreamobjectInputStream=newObjectInputStream(in); Ff=(F)objectInputStream.readObject(); assertNotNull(f); returnf; } Example12 Fromprojectand-bible,underdirectory/jsword-tweaks/bakup/. Sourcefile: Zip.java   26  publicByteArrayOutputStreamcompress()throwsIOException{ BufferedInputStreamin=newBufferedInputStream(input); ByteArrayOutputStreambos=newByteArrayOutputStream(); DeflaterOutputStreamout=newDeflaterOutputStream(bos,newDeflater(),BUF_SIZE); byte[]buf=newbyte[BUF_SIZE]; for(intcount=in.read(buf);count!=-1;count=in.read(buf)){ out.write(buf,0,count); } in.close(); out.flush(); out.close(); returnbos; } Example13 Fromprojectandroid-aac-enc,underdirectory/src/com/coremedia/iso/boxes/sampleentry/. Sourcefile: SampleEntry.java   26  publicvoid_writeChildBoxes(ByteBufferbb){ ByteArrayOutputStreambaos=newByteArrayOutputStream(); WritableByteChannelwbc=Channels.newChannel(baos); try{ for(Boxbox:boxes){ box.getBox(wbc); } wbc.close(); } catch(IOExceptione){ thrownewRuntimeException("Cannothappen.Everythingshouldbeinmemoryandthereforenoexceptions."); } bb.put(baos.toByteArray()); } Example14 Fromprojectandroid-api_1,underdirectory/android-lib/src/com/android/http/multipart/. Sourcefile: MultipartEntity.java   26  publicInputStreamgetContent()throwsIOException,IllegalStateException{ if(!isRepeatable()&&this.contentConsumed){ thrownewIllegalStateException("Contenthasbeenconsumed"); } this.contentConsumed=true; ByteArrayOutputStreambaos=newByteArrayOutputStream(); Part.sendParts(baos,this.parts,this.multipartBoundary); ByteArrayInputStreambais=newByteArrayInputStream(baos.toByteArray()); returnbais; } Example15 Fromprojectandroid-async-http,underdirectory/src/com/loopj/android/http/. Sourcefile: PersistentCookieStore.java   26  protectedStringencodeCookie(SerializableCookiecookie){ ByteArrayOutputStreamos=newByteArrayOutputStream(); try{ ObjectOutputStreamoutputStream=newObjectOutputStream(os); outputStream.writeObject(cookie); } catch(Exceptione){ returnnull; } returnbyteArrayToHexString(os.toByteArray()); } Example16 Fromprojectandroid-client_1,underdirectory/src/com/googlecode/asmack/dns/. Sourcefile: Question.java   26  publicbyte[]toByteArray()throwsIOException{ ByteArrayOutputStreambaos=newByteArrayOutputStream(512); DataOutputStreamdos=newDataOutputStream(baos); dos.write(NameUtil.toByteArray(this.name)); dos.writeShort(type.getValue()); dos.writeShort(clazz.getValue()); dos.flush(); returnbaos.toByteArray(); } Example17 Fromprojectandroid-joedayz,underdirectory/Proyectos/spring-rest-servidor/src/main/java/com/mycompany/rest/controller/. Sourcefile: PersonController.java   26  @RequestMapping(value="/person/{id}",method=RequestMethod.GET,headers="Accept=image/jpeg,image/jpg,image/png,image/gif")public@ResponseBodybyte[]getPhoto(@PathVariable("id")Longid){ try{ InputStreamis=this.getClass().getResourceAsStream("/bella.jpg"); BufferedImageimg=ImageIO.read(is); ByteArrayOutputStreambao=newByteArrayOutputStream(); ImageIO.write(img,"jpg",bao); logger.debug("Retrievingphotoasbytearrayimage"); returnbao.toByteArray(); } catch(IOExceptione){ logger.error(e); thrownewRuntimeException(e); } } Example18 FromprojectAndroid-Simple-Social-Sharing,underdirectory/SimpleSocialSharingExample/src/com/nostra13/example/socialsharing/. Sourcefile: FacebookActivity.java   26  privatevoidpublishImage(){ Bitmapbmp=((BitmapDrawable)getResources().getDrawable(R.drawable.ic_app)).getBitmap(); ByteArrayOutputStreamstream=newByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG,100,stream); byte[]bitmapdata=stream.toByteArray(); facebook.publishImage(bitmapdata,Constants.FACEBOOK_SHARE_IMAGE_CAPTION); } Example19 Fromprojectandroid-xbmcremote,underdirectory/src/org/xbmc/httpapi/client/. Sourcefile: Client.java   26  /** *Doublesthesizeofabitmapandre-readsitwithsamplesize2.I'vefoundnootherwaytosmoothelyresizeimageswithsamplesize=1. *@paramsource *@return */ privateBitmapblowup(Bitmapsource){ if(source!=null){ Bitmapbig=Bitmap.createScaledBitmap(source,source.getWidth()*2,source.getHeight()*2,true); BitmapFactory.Optionsopts=newBitmapFactory.Options(); opts.inSampleSize=2; ByteArrayOutputStreamos=newByteArrayOutputStream(); big.compress(CompressFormat.PNG,100,os); byte[]array=os.toByteArray(); returnBitmapFactory.decodeByteArray(array,0,array.length,opts); } returnnull; } Example20 Fromprojectandroidquery,underdirectory/src/com/androidquery/util/. Sourcefile: AQUtility.java   26  publicstaticbyte[]toBytes(InputStreamis){ byte[]result=null; ByteArrayOutputStreambaos=newByteArrayOutputStream(); try{ copy(is,baos); result=baos.toByteArray(); } catch(IOExceptione){ AQUtility.report(e); } close(is); returnresult; } Example21 FromprojectAndroid_1,underdirectory/org.eclipse.ecf.android/src/org/eclipse/ecf/android/. Sourcefile: SOContainer.java   26  publicstaticbyte[]serialize(Serializableobj)throwsIOException{ finalByteArrayOutputStreambos=newByteArrayOutputStream(); finalObjectOutputStreamoos=newObjectOutputStream(bos); oos.writeObject(obj); returnbos.toByteArray(); } Example22 Fromprojectandroid_external_libphonenumber,underdirectory/java/src/com/android/i18n/phonenumbers/geocoding/. Sourcefile: AreaCodeMap.java   26  /** *Getsthesizeoftheprovidedareacodemapstorage.Themapstoragepassed-inwillbefilledasaresult. */ privatestaticintgetSizeOfAreaCodeMapStorage(AreaCodeMapStorageStrategymapStorage,SortedMapareaCodeMap)throwsIOException{ mapStorage.readFromSortedMap(areaCodeMap); ByteArrayOutputStreambyteArrayOutputStream=newByteArrayOutputStream(); ObjectOutputStreamobjectOutputStream=newObjectOutputStream(byteArrayOutputStream); mapStorage.writeExternal(objectOutputStream); objectOutputStream.flush(); intsizeOfStorage=byteArrayOutputStream.size(); objectOutputStream.close(); returnsizeOfStorage; } Example23 Fromprojectandroid_packages_apps_Gallery3D,underdirectory/src/com/cooliris/picasa/. Sourcefile: GDataClient.java   26  privateByteArrayEntitygetCompressedEntity(byte[]data)throwsIOException{ ByteArrayEntityentity; if(data.length>=MIN_GZIP_SIZE){ ByteArrayOutputStreambyteOutput=newByteArrayOutputStream(data.length/2); GZIPOutputStreamgzipOutput=newGZIPOutputStream(byteOutput); gzipOutput.write(data); gzipOutput.close(); entity=newByteArrayEntity(byteOutput.toByteArray()); } else{ entity=newByteArrayEntity(data); } returnentity; } Example24 Fromprojectandroid_packages_apps_Tag,underdirectory/src/com/android/apps/tag/record/. Sourcefile: ImageRecord.java   26  publicstaticNdefRecordnewImageRecord(Bitmapbitmap){ ByteArrayOutputStreamout=newByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG,100,out); byte[]content=out.toByteArray(); returnMimeRecord.newMimeRecord("image/jpeg",content); } Example25 FromprojectAnki-Android,underdirectory/src/com/ichi2/anki/. Sourcefile: Utils.java   26  /** *Compressdata. *@parambytesToCompressisthebytearraytocompress. *@returnacompressedbytearray. *@throwsjava.io.IOException */ publicstaticbyte[]compress(byte[]bytesToCompress)throwsIOException{ Deflatercompressor=newDeflater(Deflater.BEST_COMPRESSION); compressor.setInput(bytesToCompress); compressor.finish(); ByteArrayOutputStreambos=newByteArrayOutputStream(bytesToCompress.length); byte[]buf=newbyte[bytesToCompress.length+100]; while(!compressor.finished()){ bos.write(buf,0,compressor.deflate(buf)); } bos.close(); returnbos.toByteArray(); } Example26 FromprojectANNIS,underdirectory/annis-gui/src/main/java/annis/gui/visualizers/. Sourcefile: AbstractIFrameVisualizer.java   26  @OverridepublicComponentcreateComponent(VisualizerInputvis,Applicationapplication){ AutoHeightIFrameiframe; ApplicationResourceresource; ByteArrayOutputStreamoutStream=newByteArrayOutputStream(); writeOutput(vis,outStream); resource=vis.getVisPanel().createResource(outStream,getContentType()); Stringurl=vis.getVisPanel().getApplication().getRelativeLocation(resource); iframe=newAutoHeightIFrame(url==null?"/error.html":url); returniframe; } Example27 Fromprojectannotare2,underdirectory/app/magetab/src/test/java/uk/ac/ebi/fg/annotare2/magetab/base/. Sourcefile: TsvGeneratorTest.java   26  @Testpublicvoidtest()throwsIOException{ String[]row=newString[]{"1","2","","3"}; Strings=on("\t").join(row)+"\n"; s+=s; Tabletable=newTable(); table.addRow(asList(row)); table.addRow(asList(row)); ByteArrayOutputStreamout=newByteArrayOutputStream(); newTsvGenerator(table).generate(out); Strings1=out.toString(UTF_8.name()); assertEquals(s,s1); Strings2=newTsvGenerator(table).generateString(); assertEquals(s,s2); } Example28 Fromprojectant4eclipse,underdirectory/org.ant4eclipse.lib.core.test/src-framework/org/ant4eclipse/testframework/. Sourcefile: TestDirectory.java   26  /** *Copiesthecontentfromthegiveninputstreamtothefile.

Thismethodclosestheinputstreamaftercopyingit *@paramfileNameThefilenamethatisrelativetotherootofthetestenvironment *@paraminputStreamTheinputStreamtoreadfrom *@returnThefilethathasbeencreatead *@throwsIOException */ publicFilecreateFile(StringfileName,InputStreaminputStream)throwsIOException{ ByteArrayOutputStreamoutput=newByteArrayOutputStream(); byte[]buffer=newbyte[1024]; intbytesRead=-1; while((bytesRead=inputStream.read(buffer,0,buffer.length))!=-1){ output.write(buffer,0,bytesRead); } Utilities.close(inputStream); returncreateFile(fileName,output.toString()); } Example29 Fromprojectany23,underdirectory/core/src/main/java/org/apache/any23/source/. Sourcefile: FileDocumentSource.java   26  publicStringreadStream()throwsIOException{ finalByteArrayOutputStreambaos=newByteArrayOutputStream(); InputStreamis=openInputStream(); try{ intc; while((c=is.read())!=-1){ baos.write(c); } } finally{ is.close(); } returnnewString(baos.toByteArray()); } Example30 Fromprojectapb,underdirectory/modules/test-tasks/src/apb/tests/tasks/. Sourcefile: ExecTest.java   26  staticStringinvokeExec(Stringcmd,String...args){ ByteArrayOutputStreamb=newByteArrayOutputStream(); PrintStreamprev=System.out; try{ PrintStreamp=newPrintStream(b); System.setOut(p); exec(cmd,args).execute(); p.close(); } finally{ System.setOut(prev); } returnb.toString(); } Example31 Fromprojectapg,underdirectory/src/org/thialfihar/android/apg/. Sourcefile: HkpKeyServer.java   26  staticprivateStringreadAll(InputStreamin,Stringencoding)throwsIOException{ ByteArrayOutputStreamraw=newByteArrayOutputStream(); bytebuffer[]=newbyte[1<<16]; intn=0; while((n=in.read(buffer))!=-1){ raw.write(buffer,0,n); } if(encoding==null){ encoding="utf8"; } returnraw.toString(encoding); } Example32 Fromprojectappdriver,underdirectory/android/src/com/google/android/testing/nativedriver/client/. Sourcefile: AndroidNativeDriver.java   26  protectedStringimageToBase64Png(BufferedImageimage){ ByteArrayOutputStreamrawPngStream=newByteArrayOutputStream(); try{ if(!writeImageAsPng(image,rawPngStream)){ thrownewRuntimeException("ThisJavaenvironmentdoesnotsupportconvertingtoPNG."); } } catch(IOExceptionexception){ Throwables.propagate(exception); } byte[]rawPngBytes=rawPngStream.toByteArray(); returnnewBase64Encoder().encode(rawPngBytes); } Example33 Fromprojectapps-for-android,underdirectory/Photostream/src/com/google/android/photostream/. Sourcefile: UserDatabase.java   26  staticvoidwriteBitmap(ContentValuesvalues,Stringname,Bitmapbitmap){ if(bitmap!=null){ intsize=bitmap.getWidth()*bitmap.getHeight()*2; ByteArrayOutputStreamout=newByteArrayOutputStream(size); try{ bitmap.compress(Bitmap.CompressFormat.PNG,100,out); out.flush(); out.close(); values.put(name,out.toByteArray()); } catch(IOExceptione){ } } } Example34 Fromprojectarchive-commons,underdirectory/archive-commons/src/main/java/org/archive/extract/. Sourcefile: WATExtractorOutput.java   26  privatevoidwriteWARCInfo(OutputStreamrecOut,MetaDatamd)throwsIOException{ Stringfilename=JSONUtils.extractSingle(md,"Container.Filename"); if(filename==null){ thrownewIOException("NoContainer.Filename..."); } HttpHeadersheaders=newHttpHeaders(); headers.add("Software-Info",IAUtils.COMMONS_VERSION); headers.addDateHeader("Extracted-Date",newDate()); ByteArrayOutputStreambaos=newByteArrayOutputStream(); headers.write(baos); recW.writeWARCInfoRecord(recOut,filename,baos.toByteArray()); } Example35 Fromprojectardverk-commons,underdirectory/src/main/java/org/ardverk/io/. Sourcefile: GzipCompressor.java   26  @Overridepublicbyte[]compress(byte[]value,intoffset,intlength)throwsIOException{ ByteArrayOutputStreambaos=newByteArrayOutputStream(MathUtils.nextPowOfTwo(length)); try(OutputStreamout=newGZIPOutputStream(baos)){ out.write(value,offset,length); } finally{ IoUtils.close(baos); } returnbaos.toByteArray(); } Example36 Fromproject3Dto2DApplet,underdirectory/src/java/nl/dannyarends/www/http/. Sourcefile: Webserver.java   25  voidsave(Writerw)throwsIOException{ if(expired)return; w.write(id); w.write(':'); w.write(Integer.toString(inactiveInterval)); w.write(':'); w.write(servletContext==null||servletContext.getServletContextName()==null?"":servletContext.getServletContextName()); w.write(':'); w.write(Long.toString(lastAccessTime)); w.write("\r\n"); Enumeratione=getAttributeNames(); ByteArrayOutputStreamos=newByteArrayOutputStream(1024*16); while(e.hasMoreElements()){ Stringaname=(String)e.nextElement(); Objectso=get(aname); if(soinstanceofSerializable){ os.reset(); ObjectOutputStreamoos=newObjectOutputStream(os); try{ oos.writeObject(so); w.write(aname); w.write(":"); w.write(Utils.base64Encode(os.toByteArray())); w.write("\r\n"); } catch(IOExceptionioe){ servletContext.log("Can'treplicate/storeasessionvalueof'"+aname+"'class:"+so.getClass().getName(),ioe); } } elseservletContext.log("Nonserializablesessionobjecthasbeen"+so.getClass().getName()+"skipedinstoringof"+aname,null); if(soinstanceofHttpSessionActivationListener)((HttpSessionActivationListener)so).sessionWillPassivate(newHttpSessionEvent((HttpSession)this)); } w.write("$$\r\n"); } Example37 Fromprojectactivejdbc,underdirectory/activejdbc/src/test/java/org/javalite/activejdbc/. Sourcefile: CacheEventListenerTest.java   25  @TestpublicvoidshouldNotBreakIfListenerThrowsException()throwsIOException{ classBadEventListenerimplementsCacheEventListener{ publicvoidonFlush(CacheEventevent){ thrownewRuntimeException("I'mabad,baaadlistener...."); } } BadEventListenerlistener=newBadEventListener(); Registry.cacheManager().addCacheEventListener(listener); PrintStreamerrOrig=System.err; ByteArrayOutputStreambout=newByteArrayOutputStream(); PrintStreamerr=newPrintStream(bout); System.setErr(err); Person.createIt("name","Matt","last_name","Diamont","dob","1962-01-01"); err.flush(); bout.flush(); Stringexception=bout.toString(); a(exception.contains("I'mabad,baaadlistener")).shouldBeTrue(); System.setErr(errOrig); } Example38 Fromprojectactivemq-apollo,underdirectory/apollo-openwire/src/test/scala/org/apache/activemq/apollo/openwire/codec/. Sourcefile: BooleanStreamTest.java   25  protectedvoidassertMarshalBooleans(intcount,BooleanValueSetvalueSet)throwsException{ BooleanStreambs=newBooleanStream(); for(inti=0;isyndFeed=rssService.parseRss(dataAsString); if(syndFeed!=null){ databaseService.save(dataAsString); downloadSuccess=true; } } } catch(finalThrowablet){ Ln.e(t); } finally{ closeQuietly(inputStream); } } returndownloadSuccess; } Example41 FromprojectAgot-Java,underdirectory/src/main/java/got/utility/. Sourcefile: Utility.java   25  finalstaticpublicImageloadImage(finalStringfileName){ StringkeyName=fileName.trim().toLowerCase(); ImagecacheImage=(Image)cacheImages.get(keyName); if(cacheImage==null){ InputStreamin=newBufferedInputStream(classLoader.getResourceAsStream(fileName)); ByteArrayOutputStreambyteArrayOutputStream=newByteArrayOutputStream(); try{ byte[]bytes=newbyte[8192]; intread; while((read=in.read(bytes))>=0){ byteArrayOutputStream.write(bytes,0,read); } byte[]arrayByte=byteArrayOutputStream.toByteArray(); cacheImages.put(keyName,cacheImage=toolKit.createImage(arrayByte)); mediaTracker.addImage(cacheImage,0); mediaTracker.waitForID(0); waitImage(100,cacheImage); } catch(Exceptione){ thrownewRuntimeException(fileName+"notfound!"); } finally{ try{ if(byteArrayOutputStream!=null){ byteArrayOutputStream.close(); byteArrayOutputStream=null; } if(in!=null){ in.close(); } } catch(IOExceptione){ } } } if(cacheImage==null){ thrownewRuntimeException(("Filenotfound.("+fileName+")").intern()); } returncacheImage; } Example42 Fromprojectagraph-java-client,underdirectory/src/test/. Sourcefile: RepositoryConnectionTest.java   25  @TestpublicvoidtestStatementSerialization()throwsException{ testCon.add(bob,name,nameBob); Statementst; RepositoryResultstatements=testCon.getStatements(null,null,null,true); try{ st=statements.next(); } finally{ statements.close(); } ByteArrayOutputStreambaos=newByteArrayOutputStream(); ObjectOutputStreamout=newObjectOutputStream(baos); out.writeObject(st); out.close(); ByteArrayInputStreambais=newByteArrayInputStream(baos.toByteArray()); ObjectInputStreamin=newObjectInputStream(bais); StatementdeserializedStatement=(Statement)in.readObject(); in.close(); assertTrue(st.equals(deserializedStatement)); assertTrue(testCon.hasStatement(st,true)); assertTrue(testCon.hasStatement(deserializedStatement,true)); } Example43 Fromprojectakubra,underdirectory/akubra-core/src/test/java/org/akubraproject/impl/. Sourcefile: TestStreamManager.java   25  /** *ManagedOutputStreamsshouldbetrackedwhenopenandforgottenwhenclosed. */ @Test(dependsOnGroups={"init"})publicvoidtestManageOutputStream()throwsException{ OutputStreammanaged=manager.manageOutputStream(null,newByteArrayOutputStream()); assertEquals(manager.getOpenOutputStreamCount(),1); managed.close(); assertEquals(manager.getOpenOutputStreamCount(),0); } Example44 FromprojectAlbiteREADER,underdirectory/src/org/albite/albite/. Sourcefile: AlbiteMIDlet.java   25  publicfinalvoidsaveOptionsToRMS(){ if(bookURL!=null&&!bookURL.equalsIgnoreCase("")){ try{ ByteArrayOutputStreamboas=newByteArrayOutputStream(); DataOutputStreamdout=newDataOutputStream(boas); try{ RMSHelper.writeVersionNumber(this,dout); dout.writeUTF(bookURL); dout.writeUTF(dictsFolder); byte[]data=boas.toByteArray(); if(rs.getNumRecords()>0){ rs.setRecord(1,data,0,data.length); } else{ rs.addRecord(data,0,data.length); } } catch(IOExceptionioe){ } } catch(RecordStoreExceptionrse){ } } } Example45 Fromprojectalmira-sample,underdirectory/almira-sample-client/src/test/java/almira/sample/client/. Sourcefile: ListCatapultTest.java   25  @TestpublicvoidexecutesQueryWithoutErrors(){ context.checking(newExpectations(){ { oneOf(queryService).findAll(0,MAX_RECORDS); will(returnValue(RESULT_LIST)); } } ); PrintStreamsysOut=System.out; try{ ByteArrayOutputStreambaos=newByteArrayOutputStream(); System.setOut(newPrintStream(baos)); ListCatapults.executeQuery(queryService); Assert.assertTrue("OutputcontainsCatapultname",baos.toString().contains(CATAPULT_NAME)); } finally{ System.setOut(sysOut); } } Example46 Fromprojectalphaportal_dev,underdirectory/sys-src/alphaportal_RESTClient/src/alpha/client/. Sourcefile: RESTClient.java   25  /** *readsthefileandtransformsitinapayload *@parampathpathofthefile *@paramnamenameaswhichthepayloadshouldbesaved *@returnapayload */ privatestaticPayloadreadFile(Stringpath,Payloadpayload){ InputStreaminputStream=null; try{ inputStream=newFileInputStream(path); } catch(FileNotFoundExceptione){ e.printStackTrace(); } ByteArrayOutputStreambyteBuffer=newByteArrayOutputStream(); byte[]buffer=newbyte[BUFFER_SIZE]; intreadBytes=0; try{ while(true){ readBytes=inputStream.read(buffer); if(readBytes>0){ byteBuffer.write(buffer,0,readBytes); } else{ break; } } } catch(IOExceptione){ e.printStackTrace(); } payload.setContent(byteBuffer.toByteArray()); returnpayload; } Example47 FromprojectAmoeba-for-Aladdin,underdirectory/src/java/com/meidusa/amoeba/bean/. Sourcefile: PureJavaReflectionProvider.java   25  privateObjectinstantiateUsingSerialization(Classtype){ try{ byte[]data; if(serializedDataCache.containsKey(type)){ data=(byte[])serializedDataCache.get(type); } else{ ByteArrayOutputStreambytes=newByteArrayOutputStream(); DataOutputStreamstream=newDataOutputStream(bytes); stream.writeShort(ObjectStreamConstants.STREAM_MAGIC); stream.writeShort(ObjectStreamConstants.STREAM_VERSION); stream.writeByte(ObjectStreamConstants.TC_OBJECT); stream.writeByte(ObjectStreamConstants.TC_CLASSDESC); stream.writeUTF(type.getName()); stream.writeLong(ObjectStreamClass.lookup(type).getSerialVersionUID()); stream.writeByte(2); stream.writeShort(0); stream.writeByte(ObjectStreamConstants.TC_ENDBLOCKDATA); stream.writeByte(ObjectStreamConstants.TC_NULL); data=bytes.toByteArray(); serializedDataCache.put(type,data); } ObjectInputStreamin=newObjectInputStream(newByteArrayInputStream(data)); returnin.readObject(); } catch(IOExceptione){ thrownewObjectAccessException("Cannotcreate"+type.getName()+"byJDKserialization",e); } catch(ClassNotFoundExceptione){ thrownewObjectAccessException("Cannotfindclass"+e.getMessage()); } } Example48 FromprojectAndroid-FFXIEQ,underdirectory/ffxieq/src/com/github/kanata3249/ffxieq/android/db/. Sourcefile: FFXIEQSettings.java   25  publiclongsaveCharInfo(longid,Stringname,FFXICharactercharInfo){ byte[]chardata; charInfo.reload(); try{ ObjectOutputStreamoos; ByteArrayOutputStreambaos=newByteArrayOutputStream(); ; oos=newObjectOutputStream(baos); oos.writeObject(charInfo); oos.close(); chardata=baos.toByteArray(); baos.close(); } catch(IOExceptione){ return-1; } returnsaveCharInfo(id,name,chardata,charInfo.getMeritPointId()); } Example49 Fromprojectandroid-rackspacecloud,underdirectory/extensions/bouncycastle/src/main/java/org/jclouds/encryption/bouncycastle/. Sourcefile: BouncyCastleEncryptionService.java   25  publicMD5InputStreamResultgenerateMD5Result(InputStreamtoEncode){ MD5DigesteTag=newMD5Digest(); byte[]resBuf=newbyte[eTag.getDigestSize()]; byte[]buffer=newbyte[1024]; ByteArrayOutputStreamout=newByteArrayOutputStream(); longlength=0; intnumRead=-1; try{ do{ numRead=toEncode.read(buffer); if(numRead>0){ length+=numRead; eTag.update(buffer,0,numRead); out.write(buffer,0,numRead); } } while(numRead!=-1); } catch(IOExceptione){ thrownewRuntimeException(e); } finally{ Closeables.closeQuietly(out); Closeables.closeQuietly(toEncode); } eTag.doFinal(resBuf,0); returnnewMD5InputStreamResult(out.toByteArray(),resBuf,length); } Example50 Fromprojectandroid-share-menu,underdirectory/src/com/eggie5/. Sourcefile: post_to_eggie5.java   25  publicstaticbyte[]getBytesFromFile(InputStreamis){ try{ ByteArrayOutputStreambuffer=newByteArrayOutputStream(); intnRead; byte[]data=newbyte[16384]; while((nRead=is.read(data,0,data.length))!=-1){ buffer.write(data,0,nRead); } buffer.flush(); returnbuffer.toByteArray(); } catch(IOExceptione){ Log.e("com.eggie5.post_to_eggie5",e.toString()); returnnull; } } Example51 Fromprojectandroid-shuffle,underdirectory/client/src/org/dodgybits/shuffle/android/synchronisation/tracks/. Sourcefile: WebClient.java   25  publicsynchronizedStringgetUrlContent(Stringurl)throwsApiException{ if(sUserAgent==null){ thrownewApiException("User-Agentstringmustbeprepared"); } HttpClientclient=CreateClient(); java.net.URIuri=URI.create(url); HttpHosthost=GetHost(uri); HttpGetrequest=newHttpGet(uri.getPath()); request.setHeader("User-Agent",sUserAgent); try{ HttpResponseresponse=client.execute(host,request); StatusLinestatus=response.getStatusLine(); Log.i(cTag,"getwithresponse"+status.toString()); if(status.getStatusCode()!=HttpStatus.SC_OK){ thrownewApiException("Invalidresponsefromserver:"+status.toString()); } HttpEntityentity=response.getEntity(); InputStreaminputStream=entity.getContent(); ByteArrayOutputStreamcontent=newByteArrayOutputStream(); intreadBytes; while((readBytes=inputStream.read(sBuffer))!=-1){ content.write(sBuffer,0,readBytes); } returnnewString(content.toByteArray()); } catch(IOExceptione){ thrownewApiException("ProblemcommunicatingwithAPI",e); } } Example52 Fromprojectandroid_5,underdirectory/src/aarddict/. Sourcefile: Volume.java   25  staticStringdecompressZlib(byte[]bytes)throwsIOException,DataFormatException{ Inflaterdecompressor=newInflater(); decompressor.setInput(bytes); ByteArrayOutputStreamout=newByteArrayOutputStream(); try{ byte[]buf=newbyte[1024]; while(!decompressor.finished()){ intcount=decompressor.inflate(buf); out.write(buf,0,count); } } finally{ out.close(); } returnutf8(out.toByteArray()); } Example53 Fromprojectandroid_build,underdirectory/tools/signapk/. Sourcefile: SignApk.java   25  privatestaticvoidsignWholeOutputFile(byte[]zipData,OutputStreamoutputStream,X509CertificatepublicKey,PrivateKeyprivateKey)throwsIOException,GeneralSecurityException{ if(zipData[zipData.length-22]!=0x50||zipData[zipData.length-21]!=0x4b||zipData[zipData.length-20]!=0x05||zipData[zipData.length-19]!=0x06){ thrownewIllegalArgumentException("zipdataalreadyhasanarchivecomment"); } Signaturesignature=Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); signature.update(zipData,0,zipData.length-2); ByteArrayOutputStreamtemp=newByteArrayOutputStream(); byte[]message="signedbySignApk".getBytes("UTF-8"); temp.write(message); temp.write(0); writeSignatureBlock(signature,publicKey,temp); inttotal_size=temp.size()+6; if(total_size>0xffff){ thrownewIllegalArgumentException("signatureistoobigforZIPfilecomment"); } intsignature_start=total_size-message.length-1; temp.write(signature_start&0xff); temp.write((signature_start>>8)&0xff); temp.write(0xff); temp.write(0xff); temp.write(total_size&0xff); temp.write((total_size>>8)&0xff); temp.flush(); byte[]b=temp.toByteArray(); for(inti=0;i>8)&0xff); temp.writeTo(outputStream); } Example54 Fromprojectandroid_packages_apps_Exchange,underdirectory/src/com/android/exchange/adapter/. Sourcefile: Parser.java   25  /** *Readaninlinestringfromthestream *@returntheStringasparsedfromthestream *@throwsIOException */ privateStringreadInlineString()throwsIOException{ ByteArrayOutputStreamoutputStream=newByteArrayOutputStream(256); while(true){ inti=read(); if(i==0){ break; } elseif(i==EOF_BYTE){ thrownewEofException(); } outputStream.write(i); } outputStream.flush(); Stringres=outputStream.toString("UTF-8"); outputStream.close(); returnres; } Example55 Fromprojectandroid_packages_apps_Gallery,underdirectory/src/com/android/camera/. Sourcefile: PhotoAppWidgetProvider.java   25  /** *StorethegivenbitmapinthisdatabaseforthegivenappWidgetId. */ publicbooleansetPhoto(intappWidgetId,Bitmapbitmap){ booleansuccess=false; try{ intsize=bitmap.getWidth()*bitmap.getHeight()*4; ByteArrayOutputStreamout=newByteArrayOutputStream(size); bitmap.compress(Bitmap.CompressFormat.PNG,100,out); out.flush(); out.close(); ContentValuesvalues=newContentValues(); values.put(PhotoDatabaseHelper.FIELD_APPWIDGET_ID,appWidgetId); values.put(PhotoDatabaseHelper.FIELD_PHOTO_BLOB,out.toByteArray()); SQLiteDatabasedb=getWritableDatabase(); db.insertOrThrow(PhotoDatabaseHelper.TABLE_PHOTOS,null,values); success=true; } catch(SQLiteExceptione){ Log.e(TAG,"Couldnotopendatabase",e); } catch(IOExceptione){ Log.e(TAG,"Couldnotserializephoto",e); } if(LOGD){ Log.d(TAG,"setPhotosuccess="+success); } returnsuccess; } Example56 Fromprojectandroid_packages_apps_Gallery2,underdirectory/src/com/android/gallery3d/app/. Sourcefile: MoviePlayer.java   25  publicvoidsetBookmark(Uriuri,intbookmark,intduration){ try{ BlobCachecache=CacheManager.getCache(mContext,BOOKMARK_CACHE_FILE,BOOKMARK_CACHE_MAX_ENTRIES,BOOKMARK_CACHE_MAX_BYTES,BOOKMARK_CACHE_VERSION); ByteArrayOutputStreambos=newByteArrayOutputStream(); DataOutputStreamdos=newDataOutputStream(bos); dos.writeUTF(uri.toString()); dos.writeInt(bookmark); dos.writeInt(duration); dos.flush(); cache.insert(uri.hashCode(),bos.toByteArray()); } catch(Throwablet){ Log.w(TAG,"setBookmarkfailed",t); } } Example57 Fromprojectandroid_packages_apps_Nfc,underdirectory/src/com/android/nfc/ndefpush/. Sourcefile: NdefPushProtocol.java   25  publicbyte[]toByteArray(){ ByteArrayOutputStreambuffer=newByteArrayOutputStream(1024); DataOutputStreamoutput=newDataOutputStream(buffer); try{ output.writeByte(VERSION); output.writeInt(mNumMessages); for(inti=0;ilist=newArrayList(); list.add(newPoint(0,0)); list.add(newPoint(0,100)); list.add(newPoint(100,0)); list.add(newPoint(100,100)); polyline=newPolyline(list); exporter=newPolylineExporter(); stream=newByteArrayOutputStream(); } Example60 Fromprojectardverk-dht,underdirectory/components/core/src/main/java/org/ardverk/dht/rsrc/. Sourcefile: ValueUtils.java   25  publicstaticTvalueOf(Classclazz,InputStreamin)throwsIOException{ ByteArrayOutputStreambaos=newByteArrayOutputStream(); try{ StreamUtils.copy(in,baos); } finally{ IoUtils.close(baos); } try{ Constructorconstructor=clazz.getConstructor(byte[].class); returnconstructor.newInstance(baos.toByteArray()); } catch(SecurityExceptione){ thrownewIOException("SecurityException",e); } catch(NoSuchMethodExceptione){ thrownewIOException("NoSuchMethodException",e); } catch(IllegalArgumentExceptione){ thrownewIOException("IllegalArgumentException",e); } catch(InstantiationExceptione){ thrownewIOException("InstantiationException",e); } catch(IllegalAccessExceptione){ thrownewIOException("IllegalAccessException",e); } catch(InvocationTargetExceptione){ thrownewIOException("InvocationTargetException",e); } } Example61 Fromprojectaether-core,underdirectory/aether-api/src/test/java/org/eclipse/aether/. Sourcefile: RepositoryExceptionTest.java   23  privatevoidassertSerializable(RepositoryExceptione){ try{ ObjectOutputStreamoos=newObjectOutputStream(newByteArrayOutputStream()); oos.writeObject(e); oos.close(); } catch(IOExceptionioe){ thrownewIllegalStateException(ioe); } } Example62 Fromprojectandroid-thaiime,underdirectory/latinime/src/com/android/inputmethod/deprecated/voice/. Sourcefile: RecognitionView.java   23  publicvoidshowWorking(finalByteArrayOutputStreamwaveBuffer,finalintspeechStartPosition,finalintspeechEndPosition){ mUiHandler.post(newRunnable(){ @Overridepublicvoidrun(){ mState=WORKING; prepareDialog(mContext.getText(R.string.voice_working),null,mContext.getText(R.string.cancel)); finalShortBufferbuf=ByteBuffer.wrap(waveBuffer.toByteArray()).order(ByteOrder.nativeOrder()).asShortBuffer(); buf.position(0); waveBuffer.reset(); showWave(buf,speechStartPosition/2,speechEndPosition/2); } } ); } Example63 Fromprojectandroid_packages_inputmethods_LatinIME,underdirectory/java/src/com/android/inputmethod/deprecated/voice/. Sourcefile: RecognitionView.java   23  publicvoidshowWorking(finalByteArrayOutputStreamwaveBuffer,finalintspeechStartPosition,finalintspeechEndPosition){ mUiHandler.post(newRunnable(){ @Overridepublicvoidrun(){ mState=WORKING; prepareDialog(mContext.getText(R.string.voice_working),null,mContext.getText(R.string.cancel)); finalShortBufferbuf=ByteBuffer.wrap(waveBuffer.toByteArray()).order(ByteOrder.nativeOrder()).asShortBuffer(); buf.position(0); waveBuffer.reset(); showWave(buf,speechStartPosition/2,speechEndPosition/2); } } ); }



請為這篇文章評分?