Java Code Examples for java.io.BufferedInputStream
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
public ByteArrayOutputStream compress() throws IOException { BufferedInputStream in=new BufferedInputStream(input); ByteArrayOutputStream bos=new ByteArrayOutputStream(); DeflaterOutputStream out=new DeflaterOutputStream(bos,new Deflater(),BUF_SIZE); byte[] buf=new byte[BUF_SIZE]; for (int count=in.read(buf); count != -1; count=in.read(buf)) { out.write(buf,0,count); } in.close(); out.flush(); out.close(); return bos; }
Example 2
From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.
Source file: UniversalLoader.java

byte[] bytearrayfromfile(File f) throws IOException { int filesize=(int)f.length(); byte[] buffer=new byte[filesize]; BufferedInputStream instream=new BufferedInputStream(new FileInputStream(f)); for (int i=0; i < filesize; i++) { buffer[i]=(byte)instream.read(); if (i % 1024 == 0) System.out.print("."); } return buffer; }
Example 3
From project Android-GifStitch, under directory /src/com/phunkosis/gifstitch/settings/.
Source file: GSSettings.java

public static void copyFile(File srcFile,File destFile) throws IOException { InputStream oInStream=new FileInputStream(srcFile); OutputStream oOutStream=new FileOutputStream(destFile); byte[] oBytes=new byte[1024]; int nLength; BufferedInputStream oBuffInputStream=new BufferedInputStream(oInStream); while ((nLength=oBuffInputStream.read(oBytes)) > 0) { oOutStream.write(oBytes,0,nLength); } oInStream.close(); oOutStream.close(); }
Example 4
From project Apertiurm-Androind-app-devlopment, under directory /ApertiumAndroid/src/org/apertium/android/filemanager/.
Source file: FileManager.java

public static void downloadFile(String source,String target) throws IOException { BufferedInputStream in=new BufferedInputStream(new URL(source).openStream()); java.io.FileOutputStream fos=new java.io.FileOutputStream(target); java.io.BufferedOutputStream bout=new BufferedOutputStream(fos,1024); byte data[]=new byte[1024]; while (in.read(data,0,1024) >= 0) { bout.write(data); } bout.close(); in.close(); }
Example 5
From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/.
Source file: RemoteCommandUtils.java

/** * Reads all available data from the specified input stream and writes it to the specified StringBuiler. * @param in The InputStream to read. * @param builder The StringBuilder to write to. * @throws IOException If there were any problems reading from the specified InputStream. */ private void drainInputStream(InputStream in,StringBuilder builder) throws IOException { BufferedInputStream bufferedInputStream=new BufferedInputStream(in); byte[] buffer=new byte[1024]; while (bufferedInputStream.available() > 0) { int read=bufferedInputStream.read(buffer,0,buffer.length); if (read > 0) { builder.append(new String(buffer,0,read)); } } }
Example 6
From project BBC-News-Reader, under directory /src/com/digitallizard/bbcnewsreader/resource/web/.
Source file: HtmlParser.java

/** * @param args * @throws IOException * @throws ClientProtocolException */ public static byte[] getPage(String stringUrl) throws Exception { URL url=new URL(stringUrl); URLConnection connection=url.openConnection(); System.setProperty("http.agent",""); connection.setRequestProperty("User-Agent",USER_AGENT); InputStream stream=connection.getInputStream(); BufferedInputStream inputbuffer=new BufferedInputStream(stream); ByteArrayBuffer arraybuffer=new ByteArrayBuffer(50); int current=0; while ((current=inputbuffer.read()) != -1) { arraybuffer.append((byte)current); } return arraybuffer.toByteArray(); }
Example 7
From project big-data-plugin, under directory /shims/api/src/org/pentaho/hbase/shim/api/.
Source file: HBaseValueMeta.java

/** * Decode/deserialize an object from an array of bytes * @param rawEncoded the raw encoded form * @return the deserialized object */ public static Object decodeObject(byte[] rawEncoded){ try { ByteArrayInputStream bis=new ByteArrayInputStream(rawEncoded); BufferedInputStream buf=new BufferedInputStream(bis); ObjectInputStream ois=new ObjectInputStream(buf); Object result=ois.readObject(); return result; } catch ( Exception ex) { ex.printStackTrace(); } return null; }
Example 8
From project btmidi, under directory /BluetoothMidiPlayer/src/com/noisepages/nettoyeur/midi/file/.
Source file: StandardMidiFileReader.java

public MidiFileFormat getMidiFileFormat(URL url) throws InvalidMidiDataException, IOException { InputStream urlStream=url.openStream(); BufferedInputStream bis=new BufferedInputStream(urlStream,bisBufferSize); MidiFileFormat fileFormat=null; try { fileFormat=getMidiFileFormat(bis); } finally { bis.close(); } return fileFormat; }
Example 9
From project candlepin, under directory /src/main/java/org/candlepin/config/.
Source file: ConfigurationFileLoader.java

/** * @param configurationFile config file to read * @return returns the configuration as a Map * @throws IOException thrown if there is a problem reading the file. */ public Map<String,String> loadProperties(File configurationFile) throws IOException { if (configurationFile.canRead()) { BufferedInputStream bis=new BufferedInputStream(new FileInputStream(configurationFile)); try { return loadConfiguration(bis); } finally { bis.close(); } } return new HashMap<String,String>(); }
Example 10
From project Carolina-Digital-Repository, under directory /djatoka-cdr/src/gov/lanl/adore/djatoka/util/.
Source file: IOUtils.java

public static OutputStream getOutputStream(InputStream ins,int bufferSize) throws java.io.IOException, Exception { ByteArrayOutputStream baos=new ByteArrayOutputStream(); byte[] buffer=new byte[bufferSize]; int count=0; BufferedInputStream bis=new BufferedInputStream(ins); while ((count=bis.read(buffer)) != -1) { baos.write(buffer,0,count); } baos.close(); return baos; }
Example 11
From project cidb, under directory /ncbieutils-access-service/src/main/java/edu/toronto/cs/cidb/ncbieutils/.
Source file: NCBIEUtilsAccessService.java

private org.w3c.dom.Document readXML(String url){ try { BufferedInputStream in=new BufferedInputStream(new URL(url).openStream()); DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder=dbFactory.newDocumentBuilder(); org.w3c.dom.Document result=dBuilder.parse(in); result.getDocumentElement().normalize(); return result; } catch ( Exception ex) { this.logger.error("Error while trying to retrieve data from URL " + url + " "+ ex.getClass().getName()+ " "+ ex.getMessage(),ex); return null; } }
Example 12
From project commons-compress, under directory /src/test/java/org/apache/commons/compress/.
Source file: AbstractTestCase.java

/** * Checks if an archive contains all expected files. * @param archive the archive to check * @param expected a list with expected string filenames * @throws Exception */ protected void checkArchiveContent(File archive,List<String> expected) throws Exception { final InputStream is=new FileInputStream(archive); try { final BufferedInputStream buf=new BufferedInputStream(is); final ArchiveInputStream in=factory.createArchiveInputStream(buf); this.checkArchiveContent(in,expected); } finally { is.close(); } }
Example 13
From project commons-io, under directory /src/test/java/org/apache/commons/io/input/compatibility/.
Source file: XmlStreamReader.java

private void doRawStream(InputStream is,boolean lenient) throws IOException { BufferedInputStream pis=new BufferedInputStream(is,BUFFER_SIZE); String bomEnc=getBOMEncoding(pis); String xmlGuessEnc=getXMLGuessEncoding(pis); String xmlEnc=getXmlProlog(pis,xmlGuessEnc); String encoding=calculateRawEncoding(bomEnc,xmlGuessEnc,xmlEnc,pis); prepareReader(pis,encoding); }
Example 14
From project core_1, under directory /runtime/src/main/java/org/switchyard/internal/io/graph/.
Source file: InputStreamGraph.java

/** * {@inheritDoc} */ @Override public void compose(InputStream object,Map<Integer,Object> visited) throws IOException { int bs=Serializer.DEFAULT_BUFFER_SIZE; BufferedInputStream bis=new BufferedInputStream(object,bs); ByteArrayOutputStream baos=new ByteArrayOutputStream(bs); BufferedOutputStream bos=new BufferedOutputStream(baos,bs); byte[] buff=new byte[bs]; int read=0; while ((read=bis.read(buff)) != -1) { bos.write(buff,0,read); } bos.flush(); setBytes(baos.toByteArray()); }
Example 15
From project addis, under directory /application/src/main/java/org/drugis/addis/gui/.
Source file: Main.java

private XmlFormatType loadDomainFromInputStream(InputStream in) throws IOException { BufferedInputStream fis=new BufferedInputStream(in); XmlFormatType xmlType=JAXBHandler.determineXmlType(fis); if (!xmlType.isValid() || xmlType.isFuture()) { return xmlType; } else if (xmlType.isLegacy()) { d_domainMgr.loadLegacyXMLDomain(fis); } else { d_domainMgr.loadXMLDomain(fis,xmlType.getVersion()); } attachDomainChangedModel(); return xmlType; }
Example 16
From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.
Source file: DefaultServlet.java

/** * Handle a partial PUT. New content specified in request is appended to existing content in oldRevisionContent (if present). This code does not support simultaneous partial updates to the same resource. */ protected File executePartialPut(HttpServletRequest req,Range range,String path) throws IOException { File tempDir=(File)getServletContext().getAttribute("javax.servlet.context.tempdir"); String convertedResourcePath=path.replace('/','.'); File contentFile=new File(tempDir,convertedResourcePath); if (contentFile.createNewFile()) { contentFile.deleteOnExit(); } RandomAccessFile randAccessContentFile=new RandomAccessFile(contentFile,"rw"); Resource oldResource=null; try { Object obj=resources.lookup(path); if (obj instanceof Resource) oldResource=(Resource)obj; } catch ( NamingException e) { ; } if (oldResource != null) { BufferedInputStream bufOldRevStream=new BufferedInputStream(oldResource.streamContent(),BUFFER_SIZE); int numBytesRead; byte[] copyBuffer=new byte[BUFFER_SIZE]; while ((numBytesRead=bufOldRevStream.read(copyBuffer)) != -1) { randAccessContentFile.write(copyBuffer,0,numBytesRead); } bufOldRevStream.close(); } randAccessContentFile.setLength(range.length); randAccessContentFile.seek(range.start); int numBytesRead; byte[] transferBuffer=new byte[BUFFER_SIZE]; BufferedInputStream requestBufInStream=new BufferedInputStream(req.getInputStream(),BUFFER_SIZE); while ((numBytesRead=requestBufInStream.read(transferBuffer)) != -1) { randAccessContentFile.write(transferBuffer,0,numBytesRead); } randAccessContentFile.close(); requestBufInStream.close(); return contentFile; }
Example 17
From project alljoyn_java, under directory /test/org/alljoyn/bus/.
Source file: AuthListenerTest.java

public boolean requested(String mechanism,String authPeer,int count,String userName,AuthRequest[] requests){ for ( AuthRequest request : requests) { if (request instanceof CertificateRequest) { ((CertificateRequest)request).setCertificateChain(certificate); } else if (request instanceof PrivateKeyRequest) { if (privateKey != null) { ((PrivateKeyRequest)request).setPrivateKey(privateKey); } } else if (request instanceof PasswordRequest) { if (password != null) { ((PasswordRequest)request).setPassword(password); } } else if (request instanceof VerifyRequest) { String subject=null; try { String chain=((VerifyRequest)request).getCertificateChain(); BufferedInputStream in=new BufferedInputStream(new ByteArrayInputStream(chain.getBytes())); List<X509Certificate> list=new ArrayList<X509Certificate>(); while (in.available() > 0) { list.add((X509Certificate)factory.generateCertificate(in)); } subject=list.get(0).getSubjectX500Principal().getName(X500Principal.CANONICAL).split(",")[0].split("=")[1]; CertPath path=factory.generateCertPath(list); PKIXParameters params=new PKIXParameters(trustAnchors); params.setRevocationEnabled(false); validator.validate(path,params); verified=subject; } catch ( Exception ex) { rejected=subject; return false; } } } return true; }
Example 18
From project ALP, under directory /workspace/alp-utils/src/main/java/com/lohika/alp/utils/zip/.
Source file: Zip.java

/** * Adds file to Zip. * @param filePath the file path * @throws IOException Signals that an I/O exception has occurred. */ public void add(String filePath) throws IOException { byte data[]=new byte[BUFFER]; File f=new File(filePath); if (f.isDirectory()) { File files[]=f.listFiles(); for (int i=0; i < files.length; i++) { add(files[i].getAbsolutePath()); } } else { logger.debug("Adding: " + filePath); FileInputStream fi=new FileInputStream(filePath); BufferedInputStream origin=new BufferedInputStream(fi,BUFFER); ZipEntry entry=new ZipEntry(filePath); out.putNextEntry(entry); int count; while ((count=origin.read(data,0,BUFFER)) != -1) { out.write(data,0,count); } origin.close(); } logger.debug("checksum: " + checksum.getChecksum().getValue()); }
Example 19
From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/main/java/alpha/portal/webapp/controller/.
Source file: CardFormController.java

/** * Gets the payload. * @param jspCard the jsp card * @param response the response * @return the payload * @throws IOException Signals that an I/O exception has occurred. */ @RequestMapping(method=RequestMethod.POST,params={"payloadGet"}) public String getPayload(final AlphaCard jspCard,final HttpServletResponse response) throws IOException { final AlphaCard alphaCard=this.alphaCardManager.get(jspCard.getAlphaCardIdentifier()); final Payload payload=alphaCard.getPayload(); if (payload != null) { final BufferedInputStream in=new BufferedInputStream(new ByteArrayInputStream(payload.getContent())); response.setBufferSize(payload.getContent().length); response.setContentType(payload.getMimeType()); response.setHeader("Content-Disposition","attachment; filename=\"" + payload.getFilename() + "\""); response.setContentLength(payload.getContent().length); FileCopyUtils.copy(in,response.getOutputStream()); in.close(); response.getOutputStream().flush(); response.getOutputStream().close(); } final AlphaCardIdentifier identifier=alphaCard.getAlphaCardIdentifier(); return "redirect:/caseform?caseId=" + identifier.getCaseId() + "&activeCardId="+ identifier.getCardId(); }
Example 20
From project ambrose, under directory /common/src/main/java/azkaban/common/utils/.
Source file: Props.java

public Props(Props parent,List<String> files) throws FileNotFoundException, IOException { this(parent); for (int i=0; i < files.size(); i++) { InputStream input=new BufferedInputStream(new FileInputStream(new File(files.get(i)).getAbsolutePath())); loadFrom(input); input.close(); } }
Example 21
From project Android-File-Manager, under directory /src/com/nexes/manager/.
Source file: ApplicationBackup.java

public void run(){ BufferedInputStream mBuffIn; BufferedOutputStream mBuffOut; Message msg; int len=mDataSource.size(); int read=0; for (int i=0; i < len; i++) { ApplicationInfo info=mDataSource.get(i); String source_dir=info.sourceDir; String out_file=source_dir.substring(source_dir.lastIndexOf("/") + 1,source_dir.length()); try { mBuffIn=new BufferedInputStream(new FileInputStream(source_dir)); mBuffOut=new BufferedOutputStream(new FileOutputStream(BACKUP_LOC + out_file)); while ((read=mBuffIn.read(mData,0,BUFFER)) != -1) mBuffOut.write(mData,0,read); mBuffOut.flush(); mBuffIn.close(); mBuffOut.close(); msg=new Message(); msg.what=SET_PROGRESS; msg.obj=i + " out of " + len+ " apps backed up"; mHandler.sendMessage(msg); } catch ( FileNotFoundException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } } mHandler.sendEmptyMessage(FINISH_PROGRESS); }
Example 22
From project Android-File-Manager-Tablet, under directory /src/com/nexes/manager/tablet/.
Source file: FileManager.java

/** * @param old the file to be copied * @param newDir the directory to move the file to * @return */ public int copyToDirectory(String old,String newDir){ File old_file=new File(old); File temp_dir=new File(newDir); byte[] data=new byte[BUFFER]; int read=0; if (old_file.isFile() && temp_dir.isDirectory() && temp_dir.canWrite()) { String file_name=old.substring(old.lastIndexOf("/"),old.length()); File cp_file=new File(newDir + file_name); try { BufferedOutputStream o_stream=new BufferedOutputStream(new FileOutputStream(cp_file)); BufferedInputStream i_stream=new BufferedInputStream(new FileInputStream(old_file)); while ((read=i_stream.read(data,0,BUFFER)) != -1) o_stream.write(data,0,read); o_stream.flush(); i_stream.close(); o_stream.close(); } catch ( FileNotFoundException e) { Log.e("FileNotFoundException",e.getMessage()); return -1; } catch ( IOException e) { Log.e("IOException",e.getMessage()); return -1; } } else if (old_file.isDirectory() && temp_dir.isDirectory() && temp_dir.canWrite()) { String files[]=old_file.list(); String dir=newDir + old.substring(old.lastIndexOf("/"),old.length()); int len=files.length; if (!new File(dir).mkdir()) return -1; for (int i=0; i < len; i++) copyToDirectory(old + "/" + files[i],dir); } else if (!temp_dir.canWrite()) return -1; return 0; }
Example 23
From project Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/.
Source file: AndroidFlashcards.java

private void ensureInstructions(){ File f=new File(sdDir + File.separator + "flashcards/android_flashcards_instructions.xml"); if (!f.exists()) { try { BufferedInputStream bis=new BufferedInputStream(getResources().openRawResource(R.raw.android_flashcards_instructions)); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(f)); int i; while ((i=bis.read()) != -1) bos.write(i); bos.close(); bis.close(); } catch ( Exception e) { e.printStackTrace(); } } }
Example 24
From project android-xbmcremote, under directory /src/org/xbmc/httpapi/client/.
Source file: Client.java

/** * Only downloads as much as boundaries of the image in order to find out its size. * @param manager Postback manager * @param url URL to primary cover * @param size Minmal size to pre-resize to. * @return */ private BitmapFactory.Options prefetch(INotifiableManager manager,String url,int size){ BitmapFactory.Options opts=new BitmapFactory.Options(); try { InputStream is=new BufferedInputStream(mConnection.getThumbInputStreamForMicroHTTPd(url,manager),8192); opts.inJustDecodeBounds=true; BitmapFactory.decodeStream(is,null,opts); } catch ( FileNotFoundException e) { return opts; } return opts; }
Example 25
From project android_packages_apps_Gallery, under directory /src/com/android/camera/.
Source file: ThumbnailController.java

public boolean loadData(String filePath){ FileInputStream f=null; BufferedInputStream b=null; DataInputStream d=null; try { f=new FileInputStream(filePath); b=new BufferedInputStream(f,BUFSIZE); d=new DataInputStream(b); Uri uri=Uri.parse(d.readUTF()); Bitmap thumb=BitmapFactory.decodeStream(d); setData(uri,thumb); d.close(); } catch ( IOException e) { return false; } finally { MenuHelper.closeSilently(f); MenuHelper.closeSilently(b); MenuHelper.closeSilently(d); } return true; }
Example 26
From project any23, under directory /core/src/main/java/org/apache/any23/extractor/.
Source file: SingleDocumentExtraction.java

/** * Detects the encoding of the local document source input stream. * @return a valid encoding value. */ private String detectEncoding(){ try { ensureHasLocalCopy(); InputStream is=new BufferedInputStream(localDocumentSource.openInputStream()); String encoding=this.encoderDetector.guessEncoding(is); is.close(); return encoding; } catch ( Exception e) { throw new RuntimeException("An error occurred while trying to detect the input encoding.",e); } }
Example 27
private Templates readTemplates() throws TransformerConfigurationException { InputStream xslStream=null; try { xslStream=new BufferedInputStream(new FileInputStream(styleFile)); Source src=new StreamSource(xslStream); return factory.newTemplates(src); } catch ( FileNotFoundException e) { throw new BuildException(e); } finally { StreamUtils.close(xslStream); } }
Example 28
From project apollo, under directory /injector/src/main/java/com/bskyb/cg/environments/hash/.
Source file: PersistentHash.java

private synchronized void refreshFromStore(String dirname) throws IOException { FileInputStream fis; BufferedInputStream bis; Serializable messageEntry; ObjectInputStream ois; File emptyDir=new File(dirname); FilenameFilter onlyDat=new FileExtFilter(STOREFILEEXT); File[] files=emptyDir.listFiles(onlyDat); hash.clear(); for ( File file : files) { fis=new FileInputStream(file); bis=new BufferedInputStream(fis); ois=new ObjectInputStream(bis); try { messageEntry=(Serializable)ois.readObject(); } catch ( ClassNotFoundException e) { throw new IOException(e.toString()); } catch ( ClassCastException e) { throw new IOException(e.toString()); } catch ( StreamCorruptedException e) { throw new IOException(e.toString()); } try { hash.put(file.getName(),(Message)messageEntry); } catch ( ClassCastException e) { throw new IOException(e.toString()); } fis.close(); } }
Example 29
From project ardverk-dht, under directory /components/core/src/main/java/org/ardverk/dht/io/transport/.
Source file: SocketTransport.java

private Decoder createDecoder(Socket client,final Idle idle) throws IOException { SocketAddress addr=client.getRemoteSocketAddress(); InputStream in=new BufferedInputStream(new SocketInputStream(client)); if (idle != null) { in=new ProgressInputStream(in,idle); } return codec.createDecoder(addr,in); }
Example 30
From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/parser/.
Source file: Parser.java

public void parseStream(InputStream inputStream){ try { File tmp=File.createTempFile(Parser.class.getName(),".tmp"); BufferedInputStream in=new BufferedInputStream(inputStream); BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(tmp)); byte[] buf=new byte[1024]; int len; while ((len=inputStream.read(buf)) > 0) { out.write(buf,0,len); } out.close(); in.close(); parseFileTempFile(tmp); } catch ( IOException e) { throw new ParsingException(e); } }
Example 31
From project AuToBI, under directory /src/edu/cuny/qc/speech/AuToBI/io/.
Source file: WavReader.java

/** * Constructs a WavData object from the wav file pointed to by filename. <p/> Note AuToBI currently only supports 16bit wave files. * @param filename the filename to read * @return The wav data stored in the file. * @throws IOException if there is a file reading problem * @throws UnsupportedAudioFileException if there is a problem with the audio file format * @throws AuToBIException if the file is not 16 bit */ public WavData read(String filename) throws UnsupportedAudioFileException, IOException, AuToBIException { File file=new File(filename); if (!file.exists()) { throw new AuToBIException("Wav file does not exist: " + filename); } AudioInputStream soundIn=AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(file))); return read(soundIn); }
Example 32
From project avro, under directory /lang/java/mapred/src/test/java/org/apache/avro/mapred/.
Source file: TestReflectJob.java

private void validateCountsFile(File file) throws Exception { DatumReader<WordCount> reader=new ReflectDatumReader<WordCount>(); InputStream in=new BufferedInputStream(new FileInputStream(file)); DataFileStream<WordCount> counts=new DataFileStream<WordCount>(in,reader); int numWords=0; for ( WordCount wc : counts) { assertEquals(wc.word,WordCountUtil.COUNTS.get(wc.word),(Long)wc.count); numWords++; } in.close(); assertEquals(WordCountUtil.COUNTS.size(),numWords); }
Example 33
From project azkaban, under directory /azkaban/src/java/azkaban/flow/.
Source file: ImmutableFlowManager.java

@Override public FlowExecutionHolder loadExecutableFlow(long id){ File storageFile=new File(storageDirectory,String.format("%s.json",id)); if (!storageFile.exists()) { return null; } BufferedInputStream in=null; try { in=new BufferedInputStream(new FileInputStream(storageFile)); JSONObject jsonObj=new JSONObject(Streams.asString(in)); return deserializer.apply(jsonToJava.apply(jsonObj)); } catch ( Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(in); } }
Example 34
From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/util/.
Source file: Serializer.java

/** * Uses default de-serialization to turn a byte array into an object. * @param data the byte array need to be converted * @return the converted object * @throws IOException io exception * @throws ClassNotFoundException class not found exception */ public static Object deserialize(final byte[] data) throws IOException, ClassNotFoundException { final ByteArrayInputStream bais=new ByteArrayInputStream(data); final BufferedInputStream bis=new BufferedInputStream(bais); final ObjectInputStream ois=new ObjectInputStream(bis); try { try { return ois.readObject(); } catch ( final IOException e) { throw e; } catch ( final ClassNotFoundException e) { throw e; } } finally { ois.close(); } }
Example 35
From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/processor/.
Source file: CaptchaProcessor.java

/** * Loads captcha. */ private static void loadCaptchas(){ LOGGER.info("Loading captchas...."); try { final URL captchaURL=SoloServletListener.class.getClassLoader().getResource("captcha.zip"); final ZipFile zipFile=new ZipFile(captchaURL.getFile()); final Set<String> imageNames=new HashSet<String>(); for (int row=0; row < MAX_CAPTCHA_ROW; row++) { for (int column=0; column < MAX_CAPTCHA_COLUM; column++) { imageNames.add(row + "/" + column+ ".png"); } } final ImageService imageService=ImageServiceFactory.getImageService(); final Iterator<String> i=imageNames.iterator(); while (i.hasNext()) { final String imageName=i.next(); final ZipEntry zipEntry=zipFile.getEntry(imageName); final BufferedInputStream bufferedInputStream=new BufferedInputStream(zipFile.getInputStream(zipEntry)); final byte[] captchaCharData=new byte[bufferedInputStream.available()]; bufferedInputStream.read(captchaCharData); bufferedInputStream.close(); final Image captchaChar=imageService.makeImage(captchaCharData); CAPTCHAS.put(imageName,captchaChar); } zipFile.close(); } catch ( final Exception e) { LOGGER.severe("Can not load captchs!"); throw new IllegalStateException(e); } LOGGER.info("Loaded captch images"); }
Example 36
public static BufferedInputStream bufferInput(InputStream is,int bufferSize){ if (is instanceof BufferedInputStream) { return (BufferedInputStream)is; } else { return new BufferedInputStream(is,adjustBufferSize(bufferSize)); } }
Example 37
From project behemoth, under directory /gate/src/test/java/com/digitalpebble/behemoth/gate/.
Source file: GATEProcessorTest.java

/** * Unzips the argument into the temp directory and returns the unzipped location. */ public static File unzip(File inputZip){ File rootDir=null; try { BufferedOutputStream dest=null; BufferedInputStream is=null; ZipEntry entry; ZipFile zipfile=new ZipFile(inputZip); String zipname=inputZip.getName().replaceAll("\\.zip",""); File test=File.createTempFile("aaa","aaa"); String tempDir=test.getParent(); test.delete(); rootDir=new File(tempDir,zipname); rootDir.mkdir(); Enumeration e=zipfile.entries(); while (e.hasMoreElements()) { entry=(ZipEntry)e.nextElement(); is=new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[]=new byte[BUFFER]; File target=new File(rootDir,entry.getName()); if (entry.getName().endsWith("/")) { target.mkdir(); continue; } FileOutputStream fos=new FileOutputStream(target); dest=new BufferedOutputStream(fos,BUFFER); while ((count=is.read(data,0,BUFFER)) != -1) { dest.write(data,0,count); } dest.flush(); dest.close(); is.close(); } } catch ( Exception e) { e.printStackTrace(); } return rootDir; }
Example 38
From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/vgood/.
Source file: BeintooRecomBanner.java

private void getDrawableFromUrl(final String url) throws IOException, MalformedURLException { try { new Thread(new Runnable(){ public void run(){ try { HttpURLConnection conn=(HttpURLConnection)new URL(url).openConnection(); String userAgent=getWebUserAgent(); if (userAgent != null) conn.setRequestProperty("User-Agent",userAgent); conn.connect(); InputStream is=conn.getInputStream(); BufferedInputStream bis=new BufferedInputStream(is); Bitmap bmImg=BitmapFactory.decodeStream(is); Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmImg,toDip(bmImg.getWidth()),toDip(bmImg.getHeight()),true); bis.close(); is.close(); image.setImageBitmap(resizedbitmap); UIhandler.sendEmptyMessage(0); } catch ( Exception e) { } } } ).start(); } catch ( Exception e) { e.printStackTrace(); } }
Example 39
From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/http/.
Source file: PlatoonClient.java

public static boolean cacheBadge(Context c,String h,String fName,int s){ try { String cacheDir=PublicUtils.getCachePath(c); if (!cacheDir.endsWith("/")) { cacheDir+="/"; } HttpEntity httpEntity=new RequestHandler().getHttpEntity(RequestHandler.generateUrl(URL_IMAGE,h),true); int bytesRead=0; int offset=0; int contentLength=(int)httpEntity.getContentLength(); byte[] data=new byte[contentLength]; InputStream imageStream=httpEntity.getContent(); BufferedInputStream in=new BufferedInputStream(imageStream); String filepath=cacheDir + fName; while (offset < contentLength) { bytesRead=in.read(data,offset,data.length - offset); if (bytesRead == -1) { break; } offset+=bytesRead; } if (offset != contentLength) { throw new IOException("Only read " + offset + " bytes; Expected "+ contentLength+ " bytes"); } in.close(); FileOutputStream out=new FileOutputStream(filepath); out.write(data); out.flush(); out.close(); return true; } catch ( Exception ex) { ex.printStackTrace(); return false; } }
Example 40
From project BibleQuote-for-Android, under directory /src/com/BibleQuote/utils/.
Source file: FsUtils.java

public static boolean loadContentFromURL(String fromURL,String toFile){ try { URL url=new URL("http://bible-desktop.com/xml" + fromURL); File file=new File(toFile); URLConnection ucon=url.openConnection(); InputStream is=ucon.getInputStream(); BufferedInputStream bis=new BufferedInputStream(is); ByteArrayBuffer baf=new ByteArrayBuffer(50); int current=0; while ((current=bis.read()) != -1) { baf.append((byte)current); } FileOutputStream fos=new FileOutputStream(file); fos.write(baf.toByteArray()); fos.close(); } catch ( IOException e) { Log.e(TAG,String.format("loadContentFromURL(%1$s, %2$s)",fromURL,toFile),e); return false; } return true; }
Example 41
From project bigger-tests, under directory /kernel/src/test/java/org/neo4j/kernel/impl/storemigration/.
Source file: MigrationTestUtils.java

public static void verifyFilesHaveSameContent(File original,File other) throws IOException { for ( File originalFile : original.listFiles()) { File otherFile=new File(other,originalFile.getName()); if (!originalFile.isDirectory()) { BufferedInputStream originalStream=new BufferedInputStream(new FileInputStream(originalFile)); BufferedInputStream otherStream=new BufferedInputStream(new FileInputStream(otherFile)); int aByte; while ((aByte=originalStream.read()) != -1) { assertEquals("Different content in " + originalFile.getName(),aByte,otherStream.read()); } originalStream.close(); otherStream.close(); } } }
Example 42
From project Bio-PEPA, under directory /uk.ac.ed.inf.biopepa.cl/src/uk/ac/ed/inf/biopepa/cl/.
Source file: BioPEPACommandLine.java

private static String readFileAsString(String filePath) throws java.io.IOException { byte[] buffer=new byte[(int)new File(filePath).length()]; BufferedInputStream f=null; try { f=new BufferedInputStream(new FileInputStream(filePath)); f.read(buffer); } finally { if (f != null) try { f.close(); } catch ( IOException ignored) { } } return new String(buffer); }
Example 43
From project bndtools, under directory /bndtools.bndplugins/test/test/bndtools/bndplugins/repo/git/.
Source file: TestGitOBRRepo.java

public void testGitRepoPut() throws Exception { GitOBRRepo repo=getOBRRepo(); repo.put(new BufferedInputStream(new FileInputStream("testdata/eclipse2/ploogins/javax.servlet_2.5.0.v200806031605.jar")),new RepositoryPlugin.PutOptions()); File bundleFile=repo.get("javax.servlet",new Version("2.5"),null); assertNotNull("Repository returned null",bundleFile); assertEquals(new File(checkoutDir,"jars/javax.servlet/javax.servlet-2.5.0.jar").getAbsoluteFile(),bundleFile); }
Example 44
From project BookmarksPortlet, under directory /src/main/java/edu/wisc/my/portlets/bookmarks/dao/file/.
Source file: FileSystemBookmarkStore.java

/** * @see edu.wisc.my.portlets.bookmarks.dao.BookmarkStore#getBookmarkSet(java.lang.String,java.lang.String) */ public BookmarkSet getBookmarkSet(String owner,String name){ final File storeFile=this.getStoreFile(owner,name); if (!storeFile.exists()) { return null; } try { final FileInputStream fis=new FileInputStream(storeFile); final BufferedInputStream bis=new BufferedInputStream(fis); final XMLDecoder d=new XMLDecoder(bis); try { final BookmarkSet bs=(BookmarkSet)d.readObject(); return bs; } finally { d.close(); } } catch ( FileNotFoundException fnfe) { final String errorMsg="Error reading BookmarkSet for owner='" + owner + "', name='"+ name+ "' from file='"+ storeFile+ "'"; logger.error(errorMsg,fnfe); throw new DataAccessResourceFailureException(errorMsg); } }
Example 45
From project Catroid-maven-playground, under directory /src/main/java/at/tugraz/ist/catroid/utils/.
Source file: UtilFile.java

public static File saveFileToProject(String project,String name,int fileID,Context context,int type){ String filePath; if (project == null || project.equalsIgnoreCase("")) { filePath=Utils.buildProjectPath(name); } else { switch (type) { case TYPE_IMAGE_FILE: filePath=Utils.buildPath(Utils.buildProjectPath(project),Constants.IMAGE_DIRECTORY,name); break; case TYPE_SOUND_FILE: filePath=Utils.buildPath(Utils.buildProjectPath(project),Constants.SOUND_DIRECTORY,name); break; default : filePath=Utils.buildProjectPath(name); break; } } BufferedInputStream in=new BufferedInputStream(context.getResources().openRawResource(fileID),Constants.BUFFER_8K); try { File file=new File(filePath); file.getParentFile().mkdirs(); file.createNewFile(); BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(file),Constants.BUFFER_8K); byte[] buffer=new byte[Constants.BUFFER_8K]; int length=0; while ((length=in.read(buffer)) > 0) { out.write(buffer,0,length); } in.close(); out.flush(); out.close(); return file; } catch (IOException e) { e.printStackTrace(); return null; } }
Example 46
From project CHMI, under directory /src/org/kaldax/lib/net/app/netresource/.
Source file: ActualInfo.java

private String getStringFromWebDoc(String strDocURL) throws IOException { DefaultHttpClient httpclient=new DefaultHttpClient(); HttpGet httpget=new HttpGet(strDocURL); HttpResponse response=httpclient.execute(httpget); HttpEntity entity=response.getEntity(); if (response.getStatusLine().getStatusCode() != 200) { throw new IOException("HTTP error, code=" + new Integer(response.getStatusLine().getStatusCode()).toString()); } InputStream inStream=entity.getContent(); BufferedInputStream inBuffStream=new BufferedInputStream(inStream); StringBuffer fileData=new StringBuffer(1000); byte[] buf=new byte[1024]; int numRead=0; while ((numRead=inBuffStream.read(buf)) != -1) { fileData.append(new String(buf),0,numRead); } inBuffStream.close(); return fileData.toString(); }
Example 47
public static Model parseSource(final URI location,final MimeType mimeType,final String charset,final File sourceFile) throws InterruptedException, ParserException { BufferedInputStream sourceStream=null; try { if (log.isDebugEnabled()) log.debug("Parsing '" + location + "' from file"); if (!sourceFile.exists() || !sourceFile.canRead() || sourceFile.length() == 0) { final String errorMsg=sourceFile.exists() ? "Empty resource file." : "No resource content available (2)."; log.info("Unable to parse '" + location + "'. "+ errorMsg); throw new ParserException(errorMsg,location); } sourceStream=new BufferedInputStream(new FileInputStream(sourceFile)); return parseSource(location,mimeType,charset,sourceFile.length(),sourceStream); } catch ( final Exception e) { if (e instanceof InterruptedException) throw (InterruptedException)e; if (e instanceof ParserException) throw (ParserException)e; log.error("Unexpected exception in parseSource from File: " + e.getMessage(),e); throw new ParserException("Unexpected exception: " + e.getMessage(),location); } finally { if (sourceStream != null) try { sourceStream.close(); } catch ( final Exception ex) { } } }
Example 48
From project cilia-workbench, under directory /cilia-workbench-common/src/fr/liglab/adele/cilia/workbench/common/xml/.
Source file: XMLHelpers.java

/** * Gets an Input stream from a file embedded in a jar archive. * @param jarFile the jar archive file, on the hard disk. * @param fileName the file name, in the archive. The file must be located at the archive root. * @return the input stream * @throws CiliaException if any error. */ public static InputStream inputStreamFromFileInJarArchive(File jarFile,String fileName) throws CiliaException { JarFile file; try { file=new JarFile(jarFile); } catch ( IOException e) { throw new CiliaException("Can't open jar file " + jarFile.getAbsolutePath(),e); } ZipEntry entry=file.getEntry(fileName); if (entry == null) throw new CiliaException("File " + fileName + " not found in "+ jarFile.getAbsolutePath()); BufferedInputStream is; try { is=new BufferedInputStream(file.getInputStream(entry)); } catch ( IOException e) { throw new CiliaException("Can't access file " + fileName + " in jar file "+ jarFile.getAbsolutePath(),e); } return is; }
Example 49
From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/.
Source file: ZipUtilities.java

public static void writeFileToZipFile(File file,String zippedName,ZipOutputStream zipOut) throws ZipIOException { try { byte data[]=new byte[BUFFER_SIZE]; BufferedInputStream fileInput=new BufferedInputStream(new FileInputStream(file),BUFFER_SIZE); ZipEntry entry=new ZipEntry(zippedName); zipOut.putNextEntry(entry); int count; while ((count=fileInput.read(data,0,BUFFER_SIZE)) != -1) { zipOut.write(data,0,count); } fileInput.close(); } catch ( FileNotFoundException e) { throw new ZipIOException(e.getMessage(),e); } catch ( IOException e) { throw new ZipIOException(e.getMessage(),e); } }
Example 50
From project clearcase-plugin, under directory /src/main/java/hudson/plugins/clearcase/util/.
Source file: PathUtil.java

public static String readFileAsString(String filePath) throws java.io.IOException { byte[] buffer=new byte[(int)new File(filePath).length()]; BufferedInputStream f=null; try { f=new BufferedInputStream(new FileInputStream(filePath)); f.read(buffer); } finally { if (f != null) { try { f.close(); } catch ( IOException ignored) { } } } return new String(buffer); }
Example 51
From project Clotho-Core, under directory /ClothoApps/SeqAnalyzer/src/org/clothocad/algorithm/seqanalyzer/sequencing/.
Source file: ABITrace.java

/** * The File constructor opens a local ABI file and parses the content. * @param ABIFile is a <code>java.io.File</code> on the local file system. * @throws IOException if there is a problem reading the file. * @throws IllegalArgumentException if the file is not a valid ABI file. */ public ABITrace(File ABIFile) throws IOException { byte[] bytes=null; fileName=ABIFile.getName(); ByteArrayOutputStream baos=new ByteArrayOutputStream(); FileInputStream fis=new FileInputStream(ABIFile); BufferedInputStream bis=new BufferedInputStream(fis); int b; while ((b=bis.read()) >= 0) { baos.write(b); } bis.close(); fis.close(); baos.close(); bytes=baos.toByteArray(); initData(bytes); }
Example 52
From project com.idega.content, under directory /src/java/com/idega/content/business/.
Source file: WebDAVUploadBean.java

private boolean uploadZipFile(boolean uploadingTheme) throws IOException { IWSlideService service=null; try { service=IBOLookup.getServiceInstance(IWContext.getInstance(),IWSlideService.class); } catch ( IBOLookupException e) { LOGGER.log(Level.WARNING,"Unable to get IWSlideServiceBean instance.",e); return false; } return uploadZipFile(uploadingTheme,null,new BufferedInputStream(uploadFile.getInputStream()),service); }
Example 53
From project Core_2, under directory /parser-java/src/main/java/org/jboss/forge/parser/java/util/.
Source file: Formatter.java

private static Properties readConfig(String filename){ BufferedInputStream stream=null; try { stream=new BufferedInputStream(Formatter.class.getResourceAsStream(filename)); final Properties formatterOptions=new Properties(); formatterOptions.load(stream); return formatterOptions; } catch ( IOException e) { throw new RuntimeException(e); } finally { if (stream != null) { try { stream.close(); } catch ( IOException e) { } } } }
Example 54
From project cp-common-utils, under directory /src/com/clarkparsia/common/net/.
Source file: NetworkInfo.java

private static String runCommand(String theCommand) throws IOException { Process p=Runtime.getRuntime().exec(theCommand); InputStream stdoutStream=new BufferedInputStream(p.getInputStream()); StringBuffer buffer=new StringBuffer(); for (; ; ) { int c=stdoutStream.read(); if (c == -1) break; buffer.append((char)c); } String outputText=buffer.toString(); stdoutStream.close(); return outputText; }
Example 55
From project crammer, under directory /src/main/java/uk/ac/ebi/ena/sra/cram/.
Source file: CramIndexer.java

public static void index(File cramFile,long resolution) throws Exception { ReferenceSequenceFile referenceSequenceFile; referenceSequenceFile=ReferenceDiscovery.findReferenceSequenceFileOrFail(cramFile); InputStream cramIS=new BufferedInputStream(new FileInputStream(cramFile)); OutputStream indexOS=null; indexOS=new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(cramFile + ".crai"))); index(referenceSequenceFile,cramIS,indexOS,resolution); indexOS.close(); }
Example 56
final static public Image loadImage(final String fileName){ String keyName=fileName.trim().toLowerCase(); Image cacheImage=(Image)cacheImages.get(keyName); if (cacheImage == null) { InputStream in=new BufferedInputStream(classLoader.getResourceAsStream(fileName)); ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); try { byte[] bytes=new byte[8192]; int read; 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 ( Exception e) { throw new RuntimeException(fileName + " not found!"); } finally { try { if (byteArrayOutputStream != null) { byteArrayOutputStream.close(); byteArrayOutputStream=null; } if (in != null) { in.close(); } } catch ( IOException e) { } } } if (cacheImage == null) { throw new RuntimeException(("File not found. ( " + fileName + " )").intern()); } return cacheImage; }
Example 57
From project android-aac-enc, under directory /src/com/coremedia/iso/.
Source file: PropertyBoxParserImpl.java

public PropertyBoxParserImpl(String... customProperties){ Context context=AACToM4A.getContext(); InputStream raw=null, is=null; mapping=new Properties(); try { raw=context.getResources().openRawResource(R.raw.isoparser); is=new BufferedInputStream(raw); mapping.load(is); Enumeration<URL> enumeration=Thread.currentThread().getContextClassLoader().getResources("isoparser-custom.properties"); while (enumeration.hasMoreElements()) { URL url=enumeration.nextElement(); InputStream customIS=new BufferedInputStream(url.openStream()); try { mapping.load(customIS); } finally { customIS.close(); } } for ( String customProperty : customProperties) { mapping.load(new BufferedInputStream(getClass().getResourceAsStream(customProperty))); } } catch ( IOException e) { throw new RuntimeException(e); } finally { try { if (raw != null) raw.close(); if (is != null) is.close(); } catch ( IOException e) { e.printStackTrace(); } } }
Example 58
From project android_7, under directory /src/org/immopoly/android/helper/.
Source file: WebHelper.java

public static JSONObject getHttpsData(URL url,boolean signed,Context context) throws ImmopolyException { JSONObject obj=null; if (Settings.isOnline(context)) { HttpURLConnection request; try { request=(HttpURLConnection)url.openConnection(); request.addRequestProperty("User-Agent","immopoly android client " + ImmopolyActivity.getStaticVersionInfo()); if (signed) OAuthData.getInstance(context).consumer.sign(request); request.setConnectTimeout(SOCKET_TIMEOUT); request.connect(); InputStream in=new BufferedInputStream(request.getInputStream()); String s=readInputStream(in); JSONTokener tokener=new JSONTokener(s); return new JSONObject(tokener); } catch ( JSONException e) { throw new ImmopolyException("Kommunikationsproblem (beim lesen der Antwort)",e); } catch ( MalformedURLException e) { throw new ImmopolyException("Kommunikationsproblem (fehlerhafte URL)",e); } catch ( OAuthMessageSignerException e) { throw new ImmopolyException("Kommunikationsproblem (Signierung)",e); } catch ( OAuthExpectationFailedException e) { throw new ImmopolyException("Kommunikationsproblem (Sicherherit)",e); } catch ( OAuthCommunicationException e) { throw new ImmopolyException("Kommunikationsproblem (Sicherherit)",e); } catch ( IOException e) { throw new ImmopolyException("Kommunikationsproblem",e); } } else throw new ImmopolyException("Kommunikationsproblem (Offline)"); }
Example 59
From project android_external_easymock, under directory /src/org/easymock/internal/.
Source file: EasyMockProperties.java

private EasyMockProperties(){ InputStream in=getClassLoader().getResourceAsStream("easymock.properties"); if (in != null) { in=new BufferedInputStream(in); try { properties.load(in); } catch ( IOException e) { throw new RuntimeException("Failed to read easymock.properties file"); } finally { try { in.close(); } catch ( IOException e) { } } } for ( Map.Entry<Object,Object> entry : System.getProperties().entrySet()) { if (entry.getKey() instanceof String && entry.getKey().toString().startsWith(PREFIX)) { properties.put(entry.getKey(),entry.getValue()); } } }
Example 60
From project android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/.
Source file: SaveAsActivity.java

private void saveFile(File destination){ InputStream in=null; OutputStream out=null; try { if (fileScheme) in=new BufferedInputStream(new FileInputStream(source.getPath())); else in=new BufferedInputStream(getContentResolver().openInputStream(source)); out=new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer=new byte[1024]; while (in.read(buffer) != -1) out.write(buffer); Toast.makeText(this,R.string.saveas_file_saved,Toast.LENGTH_SHORT).show(); } catch ( FileNotFoundException e) { Toast.makeText(this,R.string.saveas_error,Toast.LENGTH_SHORT).show(); } catch ( IOException e) { Toast.makeText(this,R.string.saveas_error,Toast.LENGTH_SHORT).show(); } finally { if (in != null) { try { in.close(); } catch ( IOException e) { } } if (out != null) { try { out.close(); } catch ( IOException e) { } } } }
Example 61
From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.
Source file: UriTexture.java

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,ClientConnectionManager connectionManager){ InputStream contentInput=null; if (connectionManager == null) { try { URL url=new URI(uri).toURL(); URLConnection conn=url.openConnection(); conn.connect(); contentInput=conn.getInputStream(); } catch ( Exception e) { Log.w(TAG,"Request failed: " + uri); e.printStackTrace(); return null; } } else { final DefaultHttpClient mHttpClient=new DefaultHttpClient(connectionManager,HTTP_PARAMS); HttpUriRequest request=new HttpGet(uri); HttpResponse httpResponse=null; try { httpResponse=mHttpClient.execute(request); HttpEntity entity=httpResponse.getEntity(); if (entity != null) { contentInput=entity.getContent(); } } catch ( Exception e) { Log.w(TAG,"Request failed: " + request.getURI()); return null; } } if (contentInput != null) { return new BufferedInputStream(contentInput,4096); } else { return null; } }
Example 62
From project apps-for-android, under directory /Panoramio/src/com/google/android/panoramio/.
Source file: BitmapUtils.java

/** * Loads a bitmap from the specified url. This can take a while, so it should not be called from the UI thread. * @param url The location of the bitmap asset * @return The bitmap, or null if it could not be loaded */ public static Bitmap loadBitmap(String url){ Bitmap bitmap=null; InputStream in=null; BufferedOutputStream out=null; try { in=new BufferedInputStream(new URL(url).openStream(),IO_BUFFER_SIZE); final ByteArrayOutputStream dataStream=new ByteArrayOutputStream(); out=new BufferedOutputStream(dataStream,IO_BUFFER_SIZE); copy(in,out); out.flush(); final byte[] data=dataStream.toByteArray(); bitmap=BitmapFactory.decodeByteArray(data,0,data.length); } catch ( IOException e) { Log.e(TAG,"Could not load Bitmap from: " + url); } finally { closeStream(in); closeStream(out); } return bitmap; }
Example 63
From project arquillian-container-openshift, under directory /openshift-express/src/main/java/org/jboss/arquillian/container/openshift/express/util/.
Source file: IOUtils.java

/** * Compare the contents of two Streams to determine if they are equal or not. This method buffers the input internally using BufferedInputStream if they are not already buffered. * @param input1 the first stream * @param input2 the second stream * @return true if the content of the streams are equal or they both don't exist, false otherwise * @throws NullPointerException if either input is null * @throws IOException if an I/O error occurs */ public static boolean contentEquals(InputStream input1,InputStream input2) throws IOException { if (!(input1 instanceof BufferedInputStream)) { input1=new BufferedInputStream(input1); } if (!(input2 instanceof BufferedInputStream)) { input2=new BufferedInputStream(input2); } int ch=input1.read(); while (-1 != ch) { int ch2=input2.read(); if (ch != ch2) { return false; } ch=input1.read(); } int ch2=input2.read(); return (ch2 == -1); }
Example 64
From project arquillian-container-tomcat, under directory /tomcat-common/src/main/java/org/jboss/arquillian/container/tomcat/.
Source file: CommonTomcatManager.java

public void deploy(String name,URL content) throws IOException, DeploymentException { final String contentType="application/octet-stream"; Validate.notNullOrEmpty(name,"Name must not be null or empty"); Validate.notNull(content,"Content to be deployed must not be null"); URLConnection conn=content.openConnection(); int contentLength=conn.getContentLength(); InputStream stream=new BufferedInputStream(conn.getInputStream()); StringBuilder command=new StringBuilder(getDeployCommand()); try { command.append(URLEncoder.encode(name,configuration.getUrlCharset())); } catch ( UnsupportedEncodingException e) { throw new DeploymentException("Unable to construct path for Tomcat manager",e); } execute(command.toString(),stream,contentType,contentLength); }
Example 65
From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/coreutils/.
Source file: PlatformUtil.java

/** * Utility to extract a resource file to a user configuration directory, if it does not exist - useful for setting up default configurations. * @param resourceClass class in the same package as the resourceFile toextract * @param resourceFile resource file name to extract * @return true if extracted, false otherwise (if file already exists) * @throws IOException exception thrown if extract the file failed for IOreasons */ public static boolean extractResourceToUserConfigDir(final Class resourceClass,final String resourceFile) throws IOException { final File userDir=new File(getUserConfigDirectory()); final File resourceFileF=new File(userDir + File.separator + resourceFile); if (resourceFileF.exists()) { return false; } InputStream inputStream=resourceClass.getResourceAsStream(resourceFile); OutputStream out=null; InputStream in=null; try { in=new BufferedInputStream(inputStream); OutputStream outFile=new FileOutputStream(resourceFileF); out=new BufferedOutputStream(outFile); int readBytes=0; while ((readBytes=in.read()) != -1) { out.write(readBytes); } } finally { if (in != null) { in.close(); } if (out != null) { out.flush(); out.close(); } } return true; }
Example 66
From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/pubchem/.
Source file: PubchemStructureGenerator.java

public static List<IMolecule> doDownload(String formula,IProgressMonitor monitor) throws TransformerConfigurationException, ParserConfigurationException, IOException, SAXException, FactoryConfigurationError, TransformerFactoryConfigurationError, TransformerException, NodeNotAvailableException { PubchemStructureGenerator request=new PubchemStructureGenerator(); request.submitInitalRequest(formula); worked=0; while (!request.getStatus().isFinished()) { if (monitor.isCanceled()) return null; request.refresh(); worked++; monitor.worked(worked); } request.submitDownloadRequest(); while (!request.getStatusDownload().isFinished()) { if (monitor.isCanceled()) return null; request.refresh(); worked++; monitor.worked(worked); } URLConnection uc=request.getResponseURL().openConnection(); String contentType=uc.getContentType(); int contentLength=uc.getContentLength(); if (contentType.startsWith("text/") || contentLength == -1) { throw new IOException("This is not a binary file."); } InputStream raw=uc.getInputStream(); InputStream in=new BufferedInputStream(raw); List<IMolecule> list=new ArrayList<IMolecule>(); IteratingMDLReader reader=new IteratingMDLReader(in,DefaultChemObjectBuilder.getInstance()); while (reader.hasNext()) { list.add((IMolecule)reader.next()); } return list; }
Example 67
From project C-Cat, under directory /core/src/main/java/gov/llnl/ontology/text/hbase/.
Source file: XMLRecordReader.java

/** * Extract the {@link Path} for the file to be processed by this {@link XMLRecordReader}. */ public void initialize(InputSplit isplit,TaskAttemptContext context) throws IOException, InterruptedException { Configuration config=context.getConfiguration(); FileSplit split=(FileSplit)isplit; Path file=split.getPath(); FileSystem fs=file.getFileSystem(config); fsin=(useGzip) ? new GZIPInputStream(fs.open(split.getPath())) : fs.open(split.getPath()); fsin=new BufferedInputStream(fsin); start=split.getStart(); end=start + split.getLength(); pos=0; if (!config.get(DELIMITER_TAG).equals("")) { startTag=("<" + config.get(DELIMITER_TAG)).getBytes(); endTag=("</" + config.get(DELIMITER_TAG) + ">").getBytes(); } else { String fileNameBase=file.getName().replace(".xml",""); startTag=("<" + fileNameBase).getBytes(); endTag=("</" + fileNameBase).getBytes(); } context.setStatus(file.getName() + " " + pos+ " "+ end); }
Example 68
From project Cafe, under directory /webapp/src/org/openqa/selenium/os/.
Source file: CommandLine.java

public void run(){ InputStream inputStream=new BufferedInputStream(toWatch.getInputStream()); byte[] buffer=new byte[2048]; try { int read; while ((read=inputStream.read(buffer)) > 0) { inputOut.write(buffer,0,read); inputOut.flush(); if (drainTo != null) { drainTo.write(buffer,0,read); drainTo.flush(); } } } catch ( IOException e) { } finally { try { inputOut.close(); } catch ( IOException e) { } } }
Example 69
From project ChkBugReport, under directory /src/com/sonyericsson/chkbugreport/.
Source file: Main.java

private boolean loadFrom(Module report,String fileName,InputStream is){ is=new BufferedInputStream(is,0x1000); try { is.mark(0x100); is=new GZIPInputStream(is); } catch ( IOException e) { try { is.reset(); } catch ( IOException e1) { e1.printStackTrace(); } } try { report.load(is); return true; } catch ( IOException e) { e.printStackTrace(); return false; } }
Example 70
From project Cilia_1, under directory /components/tcp-adapter/src/main/java/fr/liglab/adele/cilia/tcp/.
Source file: TCPCollector.java

public void run(){ while (started) { try { Socket s=socket.accept(); Object obj=readObject(new BufferedInputStream(s.getInputStream())); Data data=new Data(obj,"tcp-object"); notifyDataArrival(data); } catch ( IOException e) { e.printStackTrace(); } catch ( ClassNotFoundException e) { e.printStackTrace(); } } }
Example 71
From project codjo-webservices, under directory /codjo-webservices-common/src/main/java/com/tilab/wsig/.
Source file: WSIGConfiguration.java

/** * Retrieves configuration. An internal instance is loaded. */ public static void load(){ log.info("Loading WSIG configuration file..."); WSIGConfiguration c=getInstance(); InputStream is; synchronized (c) { c.setDefaultProperties(); InputStream input=null; if (wsigConfPath != null) { try { input=new FileInputStream(wsigConfPath); } catch ( FileNotFoundException e) { log.error("WSIG configuration file <<" + wsigConfPath + ">> not found, wsig agent will use default configuration",e); return; } } else { input=ClassLoader.getSystemResourceAsStream(WSIG_DEFAULT_CONFIGURATION_FILE); if (input == null) { log.error("WSIG configuration file <<" + WSIG_DEFAULT_CONFIGURATION_FILE + ">> not found, wsig agent will use default configuration"); return; } } try { is=new BufferedInputStream(input); c.load(is); is.close(); log.debug("WSIG configuration file is loaded"); } catch ( IOException e) { log.error("WSIG configuration file error reading",e); } } }
Example 72
From project components-ness-hbase, under directory /src/main/java/com/nesscomputing/hbase/spill/.
Source file: SpilledFile.java

public List<Put> load() throws IOException { InputStream is=null; final ImmutableList.Builder<Put> builder=ImmutableList.builder(); try { is=new BufferedInputStream(new FileInputStream(file)); final int skippedBytes=4 + 4 + 8; Preconditions.checkState(skippedBytes == is.skip(skippedBytes),"skipped byte mismatch (you are in trouble...)"); Put put=null; while ((put=BinaryConverter.PUT_READ_FUNCTION.apply(is)) != null) { builder.add(put); } final List<Put> result=builder.build(); Preconditions.checkState(result.size() == elements,"The preamble reported %d elements, but %d were found!",elements,result.size()); return result; } finally { Closeables.closeQuietly(is); } }
Example 73
private void sendBytes(Session sess,byte[] data,String fileName,String mode) throws IOException { OutputStream os=sess.getStdin(); InputStream is=new BufferedInputStream(sess.getStdout(),512); readResponse(is); String cline="C" + mode + " "+ data.length+ " "+ fileName+ "\n"; os.write(cline.getBytes("ISO-8859-1")); os.flush(); readResponse(is); os.write(data,0,data.length); os.write(0); os.flush(); readResponse(is); os.write("E\n".getBytes("ISO-8859-1")); os.flush(); }
Example 74
From project curator, under directory /curator-client/src/main/java/com/netflix/curator/ensemble/exhibitor/.
Source file: DefaultExhibitorRestClient.java

@Override public String getRaw(String hostname,int port,String uriPath,String mimeType) throws Exception { URI uri=new URI(useSsl ? "https" : "http",null,hostname,port,uriPath,null,null); HttpURLConnection connection=(HttpURLConnection)uri.toURL().openConnection(); connection.addRequestProperty("Accept",mimeType); StringBuilder str=new StringBuilder(); InputStream in=new BufferedInputStream(connection.getInputStream()); try { for (; ; ) { int b=in.read(); if (b < 0) { break; } str.append((char)(b & 0xff)); } } finally { Closeables.closeQuietly(in); } return str.toString(); }
Example 75
From project android-ocr, under directory /android/src/edu/sfsu/cs/orange/ocr/.
Source file: OcrInitAsyncTask.java

/** * Unzips the given Gzipped file to the given destination, and deletes the gzipped file. * @param zippedFile The gzipped file to be uncompressed * @param outFilePath File to unzip to, including path * @throws FileNotFoundException * @throws IOException */ private void gunzip(File zippedFile,File outFilePath) throws FileNotFoundException, IOException { int uncompressedFileSize=getGzipSizeUncompressed(zippedFile); Integer percentComplete; int percentCompleteLast=0; int unzippedBytes=0; final Integer progressMin=0; int progressMax=100 - progressMin; publishProgress("Uncompressing data for " + languageName + "...",progressMin.toString()); String extension=zippedFile.toString().substring(zippedFile.toString().length() - 16); if (extension.equals(".tar.gz.download")) { progressMax=50; } GZIPInputStream gzipInputStream=new GZIPInputStream(new BufferedInputStream(new FileInputStream(zippedFile))); OutputStream outputStream=new FileOutputStream(outFilePath); BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(outputStream); final int BUFFER=8192; byte[] data=new byte[BUFFER]; int len; while ((len=gzipInputStream.read(data,0,BUFFER)) > 0) { bufferedOutputStream.write(data,0,len); unzippedBytes+=len; percentComplete=(int)((unzippedBytes / (float)uncompressedFileSize) * progressMax) + progressMin; if (percentComplete > percentCompleteLast) { publishProgress("Uncompressing data for " + languageName + "...",percentComplete.toString()); percentCompleteLast=percentComplete; } } gzipInputStream.close(); bufferedOutputStream.flush(); bufferedOutputStream.close(); if (zippedFile.exists()) { zippedFile.delete(); } }
Example 76
From project android-tether, under directory /src/og/android/tether/system/.
Source file: WebserviceTask.java

public static boolean downloadBluetoothModule(String downloadFileUrl,String destinationFilename){ if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED) == false) { return false; } File bluetoothDir=new File(BLUETOOTH_FILEPATH); if (bluetoothDir.exists() == false) { bluetoothDir.mkdirs(); } if (downloadFile(downloadFileUrl,"",destinationFilename) == true) { try { FileOutputStream out=new FileOutputStream(new File(destinationFilename.replace(".gz",""))); FileInputStream fis=new FileInputStream(destinationFilename); GZIPInputStream gzin=new GZIPInputStream(new BufferedInputStream(fis)); int count; byte buf[]=new byte[8192]; while ((count=gzin.read(buf,0,8192)) != -1) { out.write(buf,0,count); } out.flush(); out.close(); gzin.close(); File inputFile=new File(destinationFilename); inputFile.delete(); } catch ( IOException e) { return false; } return true; } else return false; }
Example 77
From project android-thaiime, under directory /latinime/src/com/sugree/inputmethod/latin/.
Source file: BinaryDictionaryFileDumper.java

/** * Copies the data in an input stream to a target file if the magic number matches. If the magic number does not match the expected value, this method throws an IOException. Other usual conditions for IOException or FileNotFoundException also apply. * @param input the stream to be copied. * @param outputFile an outputstream to copy the data to. */ private static void checkMagicAndCopyFileTo(final BufferedInputStream input,final FileOutputStream output) throws FileNotFoundException, IOException { final byte[] magicNumberBuffer=new byte[MAGIC_NUMBER.length]; final int readMagicNumberSize=input.read(magicNumberBuffer,0,MAGIC_NUMBER.length); if (readMagicNumberSize < MAGIC_NUMBER.length) { throw new IOException("Less bytes to read than the magic number length"); } if (!Arrays.equals(MAGIC_NUMBER,magicNumberBuffer)) { throw new IOException("Wrong magic number for downloaded file"); } output.write(MAGIC_NUMBER); final byte[] buffer=new byte[FILE_READ_BUFFER_SIZE]; for (int readBytes=input.read(buffer); readBytes >= 0; readBytes=input.read(buffer)) output.write(buffer,0,readBytes); input.close(); }
Example 78
From project android_packages_inputmethods_LatinIME, under directory /java/src/com/android/inputmethod/latin/.
Source file: BinaryDictionaryFileDumper.java

/** * Copies the data in an input stream to a target file if the magic number matches. If the magic number does not match the expected value, this method throws an IOException. Other usual conditions for IOException or FileNotFoundException also apply. * @param input the stream to be copied. * @param outputFile an outputstream to copy the data to. */ private static void checkMagicAndCopyFileTo(final BufferedInputStream input,final FileOutputStream output) throws FileNotFoundException, IOException { final byte[] magicNumberBuffer=new byte[MAGIC_NUMBER.length]; final int readMagicNumberSize=input.read(magicNumberBuffer,0,MAGIC_NUMBER.length); if (readMagicNumberSize < MAGIC_NUMBER.length) { throw new IOException("Less bytes to read than the magic number length"); } if (!Arrays.equals(MAGIC_NUMBER,magicNumberBuffer)) { throw new IOException("Wrong magic number for downloaded file"); } output.write(MAGIC_NUMBER); final byte[] buffer=new byte[FILE_READ_BUFFER_SIZE]; for (int readBytes=input.read(buffer); readBytes >= 0; readBytes=input.read(buffer)) output.write(buffer,0,readBytes); input.close(); }
Example 79
From project anode, under directory /app/src/org/meshpoint/anode/util/.
Source file: TarExtractor.java

public void unpack(File src,File dest) throws IOException { File tarFile=new File(src.getAbsolutePath() + ".tar"); byte[] buf=new byte[1024]; GZIPInputStream zis=null; zis=new GZIPInputStream(new FileInputStream(src)); FileOutputStream tarfos=new FileOutputStream(tarFile); int count; while ((count=zis.read(buf,0,1024)) != -1) tarfos.write(buf,0,count); tarfos.close(); zis.close(); TarInputStream tis=new TarInputStream(new BufferedInputStream(new FileInputStream(tarFile))); TarEntry entry; while ((entry=tis.getNextEntry()) != null) { File entryFile=new File(dest,entry.getName()); File parentDir=new File(entryFile.getParent()); if (!parentDir.isDirectory() && !parentDir.mkdirs()) throw new IOException("TarExtractor.unpack(): unable to create directory"); FileOutputStream fos=new FileOutputStream(entryFile); BufferedOutputStream bos=new BufferedOutputStream(fos); while ((count=tis.read(buf)) != -1) bos.write(buf,0,count); bos.flush(); bos.close(); } tis.close(); tarFile.delete(); }
Example 80
From project arquillian-core, under directory /protocols/servlet/src/main/java/org/jboss/arquillian/protocol/servlet/runner/.
Source file: ServletTestRunner.java

public void executeEvent(HttpServletRequest request,HttpServletResponse response,String className,String methodName) throws ClassNotFoundException, IOException { String eventKey=className + methodName; if (request.getContentLength() > 0) { response.setStatus(HttpServletResponse.SC_NO_CONTENT); ObjectInputStream input=new ObjectInputStream(new BufferedInputStream(request.getInputStream())); Command<?> result=(Command<?>)input.readObject(); events.put(eventKey,result); } else { if (events.containsKey(eventKey) && events.get(eventKey).getResult() == null) { response.setStatus(HttpServletResponse.SC_OK); ObjectOutputStream output=new ObjectOutputStream(response.getOutputStream()); output.writeObject(events.remove(eventKey)); output.flush(); output.close(); } else { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } } }
Example 81
From project AudioBox.fm-JavaLib, under directory /audiobox.fm-sync/src/main/java/fm/audiobox/sync/task/.
Source file: MD5.java

@Override protected synchronized void doTask(){ byte[] buf=new byte[65536]; int num_read=-1; com.twmacinta.util.MD5.initNativeLibrary(true); MD5InputStream in=null; try { in=new MD5InputStream(new BufferedInputStream(new FileInputStream(this._file))); long file_length=this._file.length(), completed=0; while ((num_read=in.read(buf)) != -1) { completed+=num_read; this.getThreadListener().onProgress(this,file_length,completed,file_length - completed,this._file); } this.result=com.twmacinta.util.MD5.asHex(in.hash()); } catch ( IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch ( IOException e) { e.printStackTrace(); } } }
Example 82
From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/.
Source file: DetermineFirstSeenThread.java

@Override public void run(){ try { final URLConnection connection=new URL(Constants.BLOCKEXPLORER_BASE_URL + "address/" + address).openConnection(); connection.connect(); final Reader is=new InputStreamReader(new BufferedInputStream(connection.getInputStream())); final StringBuilder content=new StringBuilder(); IOUtils.copy(is,content); is.close(); final Matcher m=P_FIRST_SEEN.matcher(content); if (m.find()) { succeed(Iso8601Format.parseDateTime(m.group(1))); } else { succeed(null); } } catch ( final IOException x) { failed(x); } catch ( final ParseException x) { failed(x); } }
Example 83
From project bson4jackson, under directory /src/main/java/de/undercouch/bson4jackson/.
Source file: BsonParser.java

/** * Constructs a new parser * @param ctxt the Jackson IO context * @param jsonFeatures bit flag composed of bits that indicate which{@link com.fasterxml.jackson.core.JsonParser.Feature}s are enabled. * @param bsonFeatures bit flag composed of bits that indicate which{@link Feature}s are enabled. * @param in the input stream to parse. */ public BsonParser(IOContext ctxt,int jsonFeatures,int bsonFeatures,InputStream in){ super(ctxt,jsonFeatures); _bsonFeatures=bsonFeatures; _rawInputStream=in; if (!isEnabled(Feature.HONOR_DOCUMENT_LENGTH)) { if (!(in instanceof BufferedInputStream)) { in=new StaticBufferedInputStream(in); } _counter=new CountingInputStream(in); _in=new LittleEndianInputStream(_counter); } }
Example 84
From project ciel-java, under directory /examples/kmeans/src/java/skywriting/examples/kmeans/.
Source file: KMeansReducer.java

@Override public void invoke() throws Exception { KMeansMapperResult result=new KMeansMapperResult(this.k,this.numDimensions); for ( Reference pSumRef : this.partialSumsRefs) { ObjectInputStream ois=new ObjectInputStream(new FileInputStream(Ciel.RPC.getFilenameForReference(pSumRef))); KMeansMapperResult pSum=(KMeansMapperResult)ois.readObject(); result.add(pSum); ois.close(); } result.normalise(); DataInputStream oldClustersIn=new DataInputStream(new BufferedInputStream(new FileInputStream(Ciel.RPC.getFilenameForReference(this.oldClustersRef)),1048576)); double[][] oldClusters=new double[this.k][this.numDimensions]; for (int i=0; i < this.k; ++i) { for (int j=0; j < this.numDimensions; ++j) { oldClusters[i][j]=oldClustersIn.readDouble(); } } oldClustersIn.close(); double error=result.error(oldClusters); System.err.println("Iteration " + this.iteration + "; Error = "+ error); if (error > this.epsilon && this.iteration <= 20) { WritableReference newClustersOut=Ciel.RPC.getNewObjectFilename("clusters"); DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(newClustersOut.open(),1048576)); for (int i=0; i < this.k; ++i) { for (int j=0; j < result.sums[i].length; ++j) { dos.writeDouble(result.sums[i][j]); } } dos.close(); Reference newClustersRef=newClustersOut.getCompletedRef(); Reference[] newPartialSumsRefs=new Reference[this.dataPartitionsRefs.length]; for (int i=0; i < newPartialSumsRefs.length; ++i) { newPartialSumsRefs[i]=Ciel.spawn(new KMeansMapper(this.dataPartitionsRefs[i],newClustersRef,this.k,this.numDimensions,this.doCache),null,1)[0]; } Ciel.tailSpawn(new KMeansReducer(newPartialSumsRefs,newClustersRef,this.k,this.numDimensions,this.epsilon,this.dataPartitionsRefs,this.iteration + 1,this.doCache),null); } else { Ciel.returnPlainString("Finished!"); } }
Example 85
From project CircDesigNA, under directory /src/circdesigna/plugins/.
Source file: RunNupackTool.java

public static void runProcess(String string,String[] env,File nupackDir) throws IOException { System.err.println(">" + string); final Process p=Runtime.getRuntime().exec(string,env,nupackDir); if (false) { new Thread(){ public void run(){ InputStream is=new BufferedInputStream(p.getInputStream()); int ch=-1; try { while ((ch=is.read()) != -1) { System.err.print((char)ch); } } catch ( IOException e) { } } } .start(); } try { p.waitFor(); p.getOutputStream().close(); p.getInputStream().close(); p.getErrorStream().close(); } catch ( Throwable e) { e.printStackTrace(); } p.destroy(); }
Example 86
From project Cloud9, under directory /src/dist/edu/umd/hooka/alignment/.
Source file: HadoopAlign.java

static public ATable loadATable(Path path,Configuration job) throws IOException { org.apache.hadoop.conf.Configuration conf=new org.apache.hadoop.conf.Configuration(job); FileSystem fileSys=FileSystem.get(conf); DataInput in=new DataInputStream(new BufferedInputStream(fileSys.open(path))); ATable at=new ATable(); at.readFields(in); return at; }
Example 87
From project core_3, under directory /src/main/java/org/animotron/bridge/.
Source file: AbstractZipBridge.java

public void load(File file) throws IOException { if (!file.exists()) { return; } FileInputStream fis=new FileInputStream(file); ZipInputStream zis=new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; while ((entry=zis.getNextEntry()) != null) { loadEntry(zis,entry); } zis.close(); }
Example 88
From project cornerstone, under directory /frameworks/base/services/java/com/android/server/am/.
Source file: ActivityManagerService.java

private static ArrayList<ComponentName> readLastDonePreBootReceivers(){ ArrayList<ComponentName> lastDoneReceivers=new ArrayList<ComponentName>(); File file=getCalledPreBootReceiversFile(); FileInputStream fis=null; try { fis=new FileInputStream(file); DataInputStream dis=new DataInputStream(new BufferedInputStream(fis,2048)); int fvers=dis.readInt(); if (fvers == LAST_DONE_VERSION) { String vers=dis.readUTF(); String codename=dis.readUTF(); String build=dis.readUTF(); if (android.os.Build.VERSION.RELEASE.equals(vers) && android.os.Build.VERSION.CODENAME.equals(codename) && android.os.Build.VERSION.INCREMENTAL.equals(build)) { int num=dis.readInt(); while (num > 0) { num--; String pkg=dis.readUTF(); String cls=dis.readUTF(); lastDoneReceivers.add(new ComponentName(pkg,cls)); } } } } catch ( FileNotFoundException e) { } catch ( IOException e) { Slog.w(TAG,"Failure reading last done pre-boot receivers",e); } finally { if (fis != null) { try { fis.close(); } catch ( IOException e) { } } } return lastDoneReceivers; }
Example 89
From project CraftMania, under directory /CraftMania/src/org/craftmania/world/.
Source file: DefaultWorldProvider.java

@Override public void load() throws Exception { File file=Game.getInstance().getRelativeFile(Game.FILE_BASE_USER_DATA,"${world}/world.dat"); if (!file.exists()) { System.err.println("No level data found! " + file.getPath()); return; } DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(file))); _world.setTime(dis.readFloat()); _spawnPoint=new Vec3f(); IOUtilities.readVec3f(dis,_spawnPoint); readDataPointList(dis,_rawHeights); readDataPointList(dis,_heights); readDataPointList(dis,_humidities); readDataPointList(dis,_temperatures); { int size=dis.readInt(); for (int i=0; i < size; ++i) { TreeDefinition dp2d=new TreeDefinition(0,0,0,0); dp2d.x=dis.readInt(); dp2d.y=dis.readInt(); dp2d.z=dis.readInt(); dp2d.type=dis.readByte(); } } dis.close(); }
Example 90
From project cw-omnibus, under directory /EmPubLite/T16-Update/src/com/commonsware/empublite/.
Source file: DownloadInstallService.java

private static void unzip(File src,File dest) throws IOException { InputStream is=new FileInputStream(src); ZipInputStream zis=new ZipInputStream(new BufferedInputStream(is)); ZipEntry ze; dest.mkdirs(); while ((ze=zis.getNextEntry()) != null) { byte[] buffer=new byte[8192]; int count; FileOutputStream fos=new FileOutputStream(new File(dest,ze.getName())); BufferedOutputStream out=new BufferedOutputStream(fos); try { while ((count=zis.read(buffer)) != -1) { out.write(buffer,0,count); } out.flush(); } finally { fos.getFD().sync(); out.close(); } zis.closeEntry(); } zis.close(); }