Here are the examples of the java api class java.io.BufferedInputStream taken from open source projects.
1. BufferedInputStreamResetTest#testPositive()
Project: aws-sdk-java
File: BufferedInputStreamResetTest.java
File: BufferedInputStreamResetTest.java
private void testPositive(final int readLimit) throws IOException { byte[] bytes = new byte[100]; for (int i = 0; i < bytes.length; i++) bytes[i] = (byte) i; // buffer of 10 bytes BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(bytes), 10); // skip 10 bytes bis.skip(10); // buffer size would increase up to readLimit bis.mark(readLimit); // read 30 bytes in total, with internal buffer increased to 20 bis.read(new byte[20]); bis.reset(); assert (bis.read() == 10); }
2. BufferedInputStreamResetTest#testNegative()
Project: aws-sdk-java
File: BufferedInputStreamResetTest.java
File: BufferedInputStreamResetTest.java
private void testNegative(final int readLimit) throws IOException { byte[] bytes = new byte[100]; for (int i = 0; i < bytes.length; i++) bytes[i] = (byte) i; // buffer of 10 bytes BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(bytes), 10); // skip 10 bytes bis.skip(10); // 1 byte short in buffer size bis.mark(readLimit); // read 30 bytes in total, with internal buffer incread to 20 bis.read(new byte[20]); try { bis.reset(); fail(); } catch (IOException ex) { assertEquals("Resetting to invalid mark", ex.getMessage()); } }
3. ZipUtils#zipFile()
Project: SimpleExplorer
File: ZipUtils.java
File: ZipUtils.java
private static void zipFile(ZipOutputStream out, File file) throws IOException { BufferedInputStream origin; byte[] data = new byte[BUFFER]; String str = file.getPath(); FileInputStream fi = new FileInputStream(str); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(str.substring(str.lastIndexOf("/") + 1)); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } origin.close(); }
4. ProductManagementAPITest#extractBytes()
Project: shopizer
File: ProductManagementAPITest.java
File: ProductManagementAPITest.java
/** private helper methods **/ public byte[] extractBytes(File imgPath) throws Exception { FileInputStream fis = new FileInputStream(imgPath); BufferedInputStream inputStream = new BufferedInputStream(fis); byte[] fileBytes = new byte[(int) imgPath.length()]; inputStream.read(fileBytes); inputStream.close(); return fileBytes; }
5. ImageCache#readValueFromDisk()
Project: AndroidQuickUtils
File: ImageCache.java
File: ImageCache.java
@Override protected byte[] readValueFromDisk(File file) throws IOException { BufferedInputStream istream = new BufferedInputStream(new FileInputStream(file)); long fileSize = file.length(); if (fileSize > Integer.MAX_VALUE) { throw new IOException("Cannot read files larger than " + Integer.MAX_VALUE + " bytes"); } int imageDataLength = (int) fileSize; byte[] imageData = new byte[imageDataLength]; istream.read(imageData, 0, imageDataLength); istream.close(); return imageData; }
6. HttpResponseCache#readValueFromDisk()
Project: ignition
File: HttpResponseCache.java
File: HttpResponseCache.java
@Override protected ResponseData readValueFromDisk(File file) throws IOException { BufferedInputStream istream = new BufferedInputStream(new FileInputStream(file)); long fileSize = file.length(); if (fileSize > Integer.MAX_VALUE) { throw new IOException("Cannot read files larger than " + Integer.MAX_VALUE + " bytes"); } // first byte is the status code int statusCode = istream.read(); // the remainder is the response data int responseDataLength = (int) fileSize - 1; byte[] responseBody = new byte[responseDataLength]; istream.read(responseBody, 0, responseDataLength); istream.close(); return new ResponseData(statusCode, responseBody); }
7. ImageCache#readValueFromDisk()
Project: ignition
File: ImageCache.java
File: ImageCache.java
@Override protected byte[] readValueFromDisk(File file) throws IOException { BufferedInputStream istream = new BufferedInputStream(new FileInputStream(file)); long fileSize = file.length(); if (fileSize > Integer.MAX_VALUE) { throw new IOException("Cannot read files larger than " + Integer.MAX_VALUE + " bytes"); } int imageDataLength = (int) fileSize; byte[] imageData = new byte[imageDataLength]; istream.read(imageData, 0, imageDataLength); istream.close(); return imageData; }
8. CreateCollectionsTest#storeBinaryResourceFromFile()
Project: exist
File: CreateCollectionsTest.java
File: CreateCollectionsTest.java
private byte[] storeBinaryResourceFromFile(File file, Collection testCollection) throws XMLDBException, IOException { Resource res = (BinaryResource) testCollection.createResource(file.getName(), "BinaryResource"); assertNotNull("store binary Resource From File", res); // Get an array of bytes from the file: FileInputStream istr = new FileInputStream(file); // promote BufferedInputStream bstr = new BufferedInputStream(istr); // get the file size (in bytes) int size = (int) file.length(); // allocate byte array of right size byte[] data = new byte[size]; // read into byte array bstr.read(data, 0, size); bstr.close(); res.setContent(data); testCollection.storeResource(res); return data; }
9. ImageCache#readValueFromDisk()
Project: droid-fu
File: ImageCache.java
File: ImageCache.java
@Override protected byte[] readValueFromDisk(File file) throws IOException { BufferedInputStream istream = new BufferedInputStream(new FileInputStream(file)); long fileSize = file.length(); if (fileSize > Integer.MAX_VALUE) { throw new IOException("Cannot read files larger than " + Integer.MAX_VALUE + " bytes"); } int imageDataLength = (int) fileSize; byte[] imageData = new byte[imageDataLength]; istream.read(imageData, 0, imageDataLength); istream.close(); return imageData; }
10. HttpResponseCache#readValueFromDisk()
Project: droid-fu
File: HttpResponseCache.java
File: HttpResponseCache.java
@Override protected ResponseData readValueFromDisk(File file) throws IOException { BufferedInputStream istream = new BufferedInputStream(new FileInputStream(file)); long fileSize = file.length(); if (fileSize > Integer.MAX_VALUE) { throw new IOException("Cannot read files larger than " + Integer.MAX_VALUE + " bytes"); } // first byte is the status code int statusCode = istream.read(); // the remainder is the response data int responseDataLength = (int) fileSize - 1; byte[] responseBody = new byte[responseDataLength]; istream.read(responseBody, 0, responseDataLength); istream.close(); return new ResponseData(statusCode, responseBody); }
11. ProcessRealAndroidJar#addJarEntry()
Project: unmock-plugin
File: ProcessRealAndroidJar.java
File: ProcessRealAndroidJar.java
private static BufferedInputStream addJarEntry(ZipOutputStream out, File f, File root) throws IOException { int BUFFER = 2048; byte data[] = new byte[BUFFER]; BufferedInputStream origin; FileInputStream fi = new FileInputStream(f); origin = new BufferedInputStream(fi, BUFFER); String name = f.getCanonicalPath().substring(root.getCanonicalPath().length() + 1).replace('\\', '/'); JarEntry entry = new JarEntry(name); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); out.flush(); } origin.close(); return origin; }
12. CharsetFinderTest#test8BitText()
Project: community-edition
File: CharsetFinderTest.java
File: CharsetFinderTest.java
/** * Tries with various 8 bit (non-unicode) encodings, such as * ISO-8859-1 */ public void test8BitText() throws Exception { String for_iso_8859_1 = "En français où les choses sont accentués. En español, así"; String for_iso_8859_7 = "???? ????? ???? ???????? ??????"; String for_cp1251 = "??? ? ??????? ?????, ??????? ???????? ?????????"; InputStream is = new BufferedInputStream(new ByteArrayInputStream(for_iso_8859_1.getBytes("ISO-8859-1"))); Charset charset = charsetFinder.getCharset(is, MimetypeMap.MIMETYPE_TEXT_PLAIN); assertNotNull(charset); assertEquals("ISO-8859-1", charset.displayName()); is = new BufferedInputStream(new ByteArrayInputStream(for_iso_8859_7.getBytes("ISO-8859-7"))); charset = charsetFinder.getCharset(is, MimetypeMap.MIMETYPE_TEXT_PLAIN); assertNotNull(charset); assertEquals("ISO-8859-7", charset.displayName()); is = new BufferedInputStream(new ByteArrayInputStream(for_cp1251.getBytes("CP1251"))); charset = charsetFinder.getCharset(is, MimetypeMap.MIMETYPE_TEXT_PLAIN); assertNotNull(charset); // AKA CP1251 assertEquals("windows-1251", charset.displayName()); }
13. AbstractTraceReader#readFile()
Project: caffeine
File: AbstractTraceReader.java
File: AbstractTraceReader.java
/** Returns the input stream, decompressing if required. */ private InputStream readFile(String filePath) throws IOException { BufferedInputStream input = new BufferedInputStream(openFile(filePath), BUFFER_SIZE); input.mark(100); try { return new XZInputStream(input); } catch (IOException e) { input.reset(); } try { return new CompressorStreamFactory().createCompressorInputStream(input); } catch (CompressorException e) { input.reset(); } try { return new ArchiveStreamFactory().createArchiveInputStream(input); } catch (ArchiveException e) { input.reset(); } return input; }
14. BcPGPKeyRingTest#testLongSubPackets()
Project: bc-java
File: BcPGPKeyRingTest.java
File: BcPGPKeyRingTest.java
private void testLongSubPackets() throws Exception { BufferedInputStream bin = new BufferedInputStream(this.getClass().getResourceAsStream("longSigSubPack.asc")); PGPPublicKeyRing pkr = new PGPPublicKeyRing(PGPUtil.getDecoderStream(bin), new BcKeyFingerprintCalculator()); bin.close(); PGPPublicKey masterpk = pkr.getPublicKey(); // Check userids Iterator<String> uidit = masterpk.getUserIDs(); while (uidit.hasNext()) { // 1.4 compatibility checkUidSig(masterpk, (String) uidit.next()); } }
15. Md5Hasher#md5Hash()
Project: azkaban
File: Md5Hasher.java
File: Md5Hasher.java
public static byte[] md5Hash(File file) throws IOException { MessageDigest digest = getMd5Digest(); FileInputStream fStream = new FileInputStream(file); BufferedInputStream bStream = new BufferedInputStream(fStream); DigestInputStream blobStream = new DigestInputStream(bStream, digest); byte[] buffer = new byte[BYTE_BUFFER_SIZE]; int num = 0; do { num = blobStream.read(buffer); } while (num > 0); bStream.close(); return digest.digest(); }
16. system#compress()
Project: AndroidQuickUtils
File: system.java
File: system.java
/** * Compresses a single file (source) and prepares a zip file (target) * * @param source * @param target * @throws IOException */ public static void compress(File source, File target) throws IOException { ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target))); ZipEntry zipEntry = new ZipEntry(source.getName()); zipOut.putNextEntry(zipEntry); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source), BUFFER); byte data[] = new byte[BUFFER]; int count = 0; while ((count = bis.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } bis.close(); zipOut.close(); }
17. Zipper#zip()
Project: XM-File-Format
File: Zipper.java
File: Zipper.java
/* * Opens the destination into a checked output stream for checksum generation. Data is loaded in * from the files. Has a hard buffer of 4096. This is not a batch method. * * @param input the files to be inflated * @param destination the zip destination for the inflated files * * @return the checksum generated */ public static long zip(File input, File destination) throws IOException { final CheckedOutputStream checksum = new CheckedOutputStream(new FileOutputStream(destination), new Adler32()); final ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(checksum)); byte[] data = new byte[4096]; final BufferedInputStream origin = new BufferedInputStream(new FileInputStream(input), 4096); final ZipEntry entry = new ZipEntry(input.getAbsolutePath()); out.putNextEntry(entry); int count; while ((count = origin.read(data)) != -1) out.write(data, 0, count); origin.close(); out.close(); checksum.close(); return checksum.getChecksum().getValue(); }
18. SerDesTest4#readIn()
Project: uima-uimaj
File: SerDesTest4.java
File: SerDesTest4.java
private byte[] readIn(String fname) throws IOException { File f = new File("src/test/resources/SerDes4/" + fname + ".binary"); int len = (int) f.length(); byte[] buffer = new byte[len]; BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(f)); int br = inStream.read(buffer); if (br != len) { assertTrue(false); } inStream.close(); return buffer; }
19. PlasticClassPool#readClassNode()
Project: tapestry-5
File: PlasticClassPool.java
File: PlasticClassPool.java
static ClassNode readClassNode(String className, ClassLoader classLoader) throws IOException { ClassNode classNode = new ClassNode(); final String location = PlasticInternalUtils.toInternalName(className) + ".class"; InputStream inputStream = classLoader.getResourceAsStream(location); BufferedInputStream bis = new BufferedInputStream(inputStream); ClassReader classReader = new ClassReader(inputStream); inputStream.close(); bis.close(); classReader.accept(classNode, 0); return classNode; }
20. RandomInputStream#compareStreams()
Project: jackrabbit
File: RandomInputStream.java
File: RandomInputStream.java
public static void compareStreams(InputStream a, InputStream b) throws IOException { a = new BufferedInputStream(a); b = new BufferedInputStream(b); long pos = 0; while (true) { int x = a.read(); int y = b.read(); if (x == -1 || y == -1) { if (x == y) { break; } } if (x != y) { throw new IOException("Incorrect byte at position " + pos + ": x=" + x + " y=" + y); } } }
21. TestInfoServers#getUrlContent()
Project: hindex
File: TestInfoServers.java
File: TestInfoServers.java
private String getUrlContent(URL u) throws IOException { java.net.URLConnection c = u.openConnection(); c.connect(); StringBuilder sb = new StringBuilder(); BufferedInputStream bis = new BufferedInputStream(c.getInputStream()); byte[] bytes = new byte[1024]; for (int read = -1; (read = bis.read(bytes)) != -1; ) { sb.append(new String(bytes, 0, read)); } bis.close(); String content = sb.toString(); return content; }
22. ZipWriter#addFile()
Project: guvnor
File: ZipWriter.java
File: ZipWriter.java
public void addFile(final ZipEntry zipEntry, final InputStream inputStream) throws IOException { final int BUFFER = 2048; byte data[] = new byte[BUFFER]; BufferedInputStream origin = new BufferedInputStream(inputStream, BUFFER); outputStream.putNextEntry(zipEntry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { outputStream.write(data, 0, count); } outputStream.flush(); origin.close(); }
23. TaskCompressLZMA#doTask()
Project: ForgeGradle
File: TaskCompressLZMA.java
File: TaskCompressLZMA.java
//@formatter:on @TaskAction public void doTask() throws IOException { final BufferedInputStream in = new BufferedInputStream(new FileInputStream(getInputFile())); final OutputStream out = new LzmaOutputStream.Builder(new FileOutputStream(getOutputFile())).useEndMarkerMode(true).build(); ByteStreams.copy(in, out); in.close(); out.close(); }
24. FileCompare#compareBytes()
Project: fop
File: FileCompare.java
File: FileCompare.java
/** * Compare the contents of two files. * @param file1 the first file to compare * @param file2 the second file to compare * @return true if files are same byte-by-byte, false otherwise */ private static boolean compareBytes(File file1, File file2) throws IOException { boolean same = true; BufferedInputStream file1Input = new BufferedInputStream(new java.io.FileInputStream(file1)); BufferedInputStream file2Input = new BufferedInputStream(new java.io.FileInputStream(file2)); int charact1 = 0; int charact2 = 0; while (charact1 != -1) { if (charact1 == charact2) { charact1 = file1Input.read(); charact2 = file2Input.read(); } else { same = false; break; } } IOUtils.closeQuietly(file1Input); IOUtils.closeQuietly(file2Input); return same; }
25. SWCFileSpecification#createNIOReader()
Project: flex-falcon
File: SWCFileSpecification.java
File: SWCFileSpecification.java
private Reader createNIOReader() throws IOException { InputStream strm = createInputStream(); BufferedInputStream bufferedStrm; if (strm instanceof BufferedInputStream) bufferedStrm = (BufferedInputStream) strm; else bufferedStrm = new BufferedInputStream(strm); // Skip BOM header. final BOM bom = getBOM(bufferedStrm); bufferedStrm.skip(bom.pattern.length); return new BufferedReader(new InputStreamReader(bufferedStrm, bom.charset)); }
26. FileSpecification#createNIOReader()
Project: flex-falcon
File: FileSpecification.java
File: FileSpecification.java
private Reader createNIOReader() throws IOException { final File file = getFileHandle(); // Skip BOM header. final BufferedInputStream strm = new BufferedInputStream(new FileInputStream(file)); final BOM bom = getBOM(strm); strm.skip(bom.pattern.length); final Reader reader = new BufferedReader(new InputStreamReader(strm, bom.charset)); return reader; }
27. ImageUtil#decodeSampledBitmapFromStream()
Project: DesignOverlay-Android
File: ImageUtil.java
File: ImageUtil.java
public static Bitmap decodeSampledBitmapFromStream(InputStream inputStream, int reqWidth, int reqHeight) { final BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); bufferedInputStream.mark(Integer.MAX_VALUE); // First decode with inJustDecodeBounds = true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(bufferedInputStream, null, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); try { bufferedInputStream.reset(); } catch (IOException e) { Timber.w("Could not reposition the stream:" + e); } // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeStream(bufferedInputStream, null, options); }
28. ClobTest#transferData()
Project: derby
File: ClobTest.java
File: ClobTest.java
/** * Transfer data from an input stream to an output stream. * * @param source source data * @param dest destination to write to * @param tz buffer size in number of bytes. Must be 1 or greater. * @return Number of bytes read from the source data. This should equal the * number of bytes written to the destination. */ private int transferData(InputStream source, OutputStream dest, int tz) throws IOException { if (tz < 1) { throw new IllegalArgumentException("Buffer size must be 1 or greater: " + tz); } BufferedInputStream in = new BufferedInputStream(source); BufferedOutputStream out = new BufferedOutputStream(dest, tz); byte[] bridge = new byte[tz]; int total = 0; int read; while ((read = in.read(bridge, 0, tz)) != -1) { out.write(bridge, 0, read); total += read; } in.close(); // Don't close the stream, in case it will be written to again. out.flush(); return total; }
29. CrashHandler#getCrashFile()
Project: spacewalk
File: CrashHandler.java
File: CrashHandler.java
/** * Download a base64 encoded crash file. * @param loggedInUser The current user * @param crashFileId Crash File ID * @return Return a byte array of the crash file. * @throws IOException if there is an exception * * @xmlrpc.doc Download a crash file. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param("int", "crashFileId") * @xmlrpc.returntype base64 - base64 encoded crash file. */ public byte[] getCrashFile(User loggedInUser, Integer crashFileId) throws IOException { CrashFile crashFile = CrashManager.lookupCrashFileByUserAndId(loggedInUser, new Long(crashFileId.longValue())); String path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + crashFile.getCrash().getStoragePath() + "/" + crashFile.getFilename(); File file = new File(path); if (file.length() > freeMemCoeff * Runtime.getRuntime().freeMemory()) { throw new CrashFileDownloadException("api.crashfile.download.toolarge"); } byte[] plainFile = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); BufferedInputStream br = new BufferedInputStream(fis); if (br.read(plainFile) != file.length()) { throw new CrashFileDownloadException("api.package.download.ioerror"); } fis.close(); br.close(); return Base64.encodeBase64(plainFile); }
30. LocalPaginatedStorageRestoreTx#copyFile()
Project: orientdb
File: LocalPaginatedStorageRestoreTx.java
File: LocalPaginatedStorageRestoreTx.java
private static void copyFile(String from, String to) throws IOException { final File fromFile = new File(from); FileInputStream fromInputStream = new FileInputStream(fromFile); BufferedInputStream fromBufferedStream = new BufferedInputStream(fromInputStream); FileOutputStream toOutputStream = new FileOutputStream(to); byte[] data = new byte[1024]; int bytesRead = fromBufferedStream.read(data); while (bytesRead > 0) { toOutputStream.write(data, 0, bytesRead); bytesRead = fromBufferedStream.read(data); } fromBufferedStream.close(); toOutputStream.close(); }
31. LocalPaginatedStorageRestoreFromWAL#copyFile()
Project: orientdb
File: LocalPaginatedStorageRestoreFromWAL.java
File: LocalPaginatedStorageRestoreFromWAL.java
private static void copyFile(String from, String to) throws IOException { final File fromFile = new File(from); FileInputStream fromInputStream = new FileInputStream(fromFile); BufferedInputStream fromBufferedStream = new BufferedInputStream(fromInputStream); FileOutputStream toOutputStream = new FileOutputStream(to); byte[] data = new byte[1024]; int bytesRead = fromBufferedStream.read(data); while (bytesRead > 0) { toOutputStream.write(data, 0, bytesRead); bytesRead = fromBufferedStream.read(data); } fromBufferedStream.close(); toOutputStream.close(); }
32. BinaryCompare#compare()
Project: log4j
File: BinaryCompare.java
File: BinaryCompare.java
/** * Compares two files using binary comparison. * * @param file1 * @param file2 * @return true if they are the same * @throws FileNotFoundException * @throws IOException */ public static boolean compare(final String file1, final String file2) throws FileNotFoundException, IOException { BufferedInputStream in1 = new BufferedInputStream(new FileInputStream(file1)); BufferedInputStream in2 = new BufferedInputStream(new FileInputStream(file2)); try { return compare(file1, file2, in1, in2); } finally { in1.close(); in2.close(); } }
33. TelnetClient#_connectAction_()
Project: commons-net
File: TelnetClient.java
File: TelnetClient.java
/*** * Handles special connection requirements. * * @throws IOException If an error occurs during connection setup. ***/ @Override protected void _connectAction_() throws IOException { super._connectAction_(); TelnetInputStream tmp = new TelnetInputStream(_input_, this, readerThread); if (readerThread) { tmp._start(); } // __input CANNOT refer to the TelnetInputStream. We run into // blocking problems when some classes use TelnetInputStream, so // we wrap it with a BufferedInputStream which we know is safe. // This blocking behavior requires further investigation, but right // now it looks like classes like InputStreamReader are not implemented // in a safe manner. __input = new BufferedInputStream(tmp); __output = new TelnetOutputStream(this); }
34. StandardSerializer#deSerialize()
Project: commons-jcs
File: StandardSerializer.java
File: StandardSerializer.java
/** * Uses default de-serialization to turn a byte array into an object. All exceptions are * converted into IOExceptions. * <p> * @param data * @return Object * @throws IOException * @throws ClassNotFoundException */ @Override public <T> T deSerialize(byte[] data, ClassLoader loader) throws IOException, ClassNotFoundException { ByteArrayInputStream bais = new ByteArrayInputStream(data); BufferedInputStream bis = new BufferedInputStream(bais); ObjectInputStream ois = new ObjectInputStreamClassLoaderAware(bis, loader); try { // Need to cast from Object @SuppressWarnings("unchecked") T readObject = (T) ois.readObject(); return readObject; } finally { ois.close(); } }
35. CompressingSerializer#deserializeObject()
Project: commons-jcs
File: CompressingSerializer.java
File: CompressingSerializer.java
/** * Does the standard deserialization. * <p> * @param decompressedByteArray array of decompressed bytes * @return Object * @throws IOException on i/o error * @throws ClassNotFoundException if class is not found during deserialization */ protected <T> T deserializeObject(byte[] decompressedByteArray) throws IOException, ClassNotFoundException { ByteArrayInputStream bais = new ByteArrayInputStream(decompressedByteArray); BufferedInputStream bis = new BufferedInputStream(bais); ObjectInputStream ois = new ObjectInputStreamClassLoaderAware(bis, null); try { // Need to cast from Object @SuppressWarnings("unchecked") T readObject = (T) ois.readObject(); return readObject; } finally { ois.close(); } }
36. XmlStreamReader#doHttpStream()
Project: commons-io
File: XmlStreamReader.java
File: XmlStreamReader.java
private void doHttpStream(final InputStream is, final String httpContentType, final boolean lenient) throws IOException { final BufferedInputStream pis = new BufferedInputStream(is, BUFFER_SIZE); final String cTMime = getContentTypeMime(httpContentType); final String cTEnc = getContentTypeEncoding(httpContentType); final String bomEnc = getBOMEncoding(pis); final String xmlGuessEnc = getXMLGuessEncoding(pis); final String xmlEnc = getXmlProlog(pis, xmlGuessEnc); final String encoding = calculateHttpEncoding(cTMime, cTEnc, bomEnc, xmlGuessEnc, xmlEnc, pis, lenient); prepareReader(pis, encoding); }
37. MimeMessageParser#getContent()
Project: commons-email
File: MimeMessageParser.java
File: MimeMessageParser.java
/** * Read the content of the input stream. * * @param is the input stream to process * @return the content of the input stream * @throws IOException reading the input stream failed */ private byte[] getContent(final InputStream is) throws IOException { int ch; byte[] result; final ByteArrayOutputStream os = new ByteArrayOutputStream(); final BufferedInputStream isReader = new BufferedInputStream(is); final BufferedOutputStream osWriter = new BufferedOutputStream(os); while ((ch = isReader.read()) != -1) { osWriter.write(ch); } osWriter.flush(); result = os.toByteArray(); osWriter.close(); return result; }
38. DetectArchiverTestCase#checkEmptyArchive()
Project: commons-compress
File: DetectArchiverTestCase.java
File: DetectArchiverTestCase.java
private void checkEmptyArchive(final String type) throws Exception { // will be deleted by tearDown() final File ar = createEmptyArchive(type); // Just in case file cannot be deleted ar.deleteOnExit(); ArchiveInputStream ais = null; BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(ar)); ais = factory.createArchiveInputStream(in); } catch (final ArchiveException ae) { fail("Should have recognized empty archive for " + type); } finally { if (ais != null) { // will close input as well ais.close(); } else if (in != null) { in.close(); } } }
39. BCELifierTestCase#exec()
Project: commons-bcel
File: BCELifierTestCase.java
File: BCELifierTestCase.java
private String exec(final File workDir, final String... args) throws Exception { // System.err.println(java.util.Arrays.toString(args)); final ProcessBuilder pb = new ProcessBuilder(args); pb.directory(workDir); final Process proc = pb.start(); try (BufferedInputStream is = new BufferedInputStream(proc.getInputStream()); InputStream es = proc.getErrorStream()) { proc.waitFor(); final byte[] buff = new byte[2048]; int len; while ((len = es.read(buff)) != -1) { System.err.print(new String(buff, 0, len)); } final StringBuilder sb = new StringBuilder(); while ((len = is.read(buff)) != -1) { sb.append(new String(buff, 0, len)); } return sb.toString(); } }
40. MultipartParser#parseParts()
Project: cocoon
File: MultipartParser.java
File: MultipartParser.java
private void parseParts(int contentLength, String contentType, InputStream requestStream) throws IOException, MultipartException { this.contentLength = contentLength; if (contentLength > this.maxUploadSize) { this.oversized = true; } BufferedInputStream bufferedStream = new BufferedInputStream(requestStream); PushbackInputStream pushbackStream = new PushbackInputStream(bufferedStream, MAX_BOUNDARY_SIZE); TokenStream stream = new TokenStream(pushbackStream); parseMultiPart(stream, getBoundary(contentType)); }
41. JPEGSourceInspector#isImageFileType()
Project: cocoon
File: JPEGSourceInspector.java
File: JPEGSourceInspector.java
/** * Checks that this is in fact a jpeg file. */ protected final boolean isImageFileType(Source source) throws SourceException { BufferedInputStream in = null; try { in = new BufferedInputStream(source.getInputStream()); byte[] buf = new byte[2]; int count = in.read(buf, 0, 2); if (count < 2) return false; if ((buf[0] == (byte) 0xFF) && (buf[1] == (byte) 0xD8)) return true; } catch (IOException ioe) { throw new SourceException("Could not read source", ioe); } finally { if (in != null) try { in.close(); } catch (Exception e) { } } return false; }
42. GIFSourceInspector#isImageFileType()
Project: cocoon
File: GIFSourceInspector.java
File: GIFSourceInspector.java
/** * Checks that this is in fact a gif file. */ protected final boolean isImageFileType(Source source) throws SourceException { BufferedInputStream in = null; try { in = new BufferedInputStream(source.getInputStream()); byte[] buf = new byte[3]; int count = in.read(buf, 0, 3); if (count < 3) return false; if ((buf[0] == (byte) 'G') && (buf[1] == (byte) 'I') && (buf[2] == (byte) 'F')) return true; } catch (IOException ioe) { throw new SourceException("Could not read source", ioe); } finally { if (in != null) try { in.close(); } catch (Exception e) { } } return false; }
43. HtmlImage#setSampleSize()
Project: cgeo
File: HtmlImage.java
File: HtmlImage.java
private void setSampleSize(final File file, final BitmapFactory.Options bfOptions) { //Decode image size only final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BufferedInputStream stream = null; try { stream = new BufferedInputStream(new FileInputStream(file)); BitmapFactory.decodeStream(stream, null, options); } catch (final FileNotFoundException e) { Log.e("HtmlImage.setSampleSize", e); } finally { IOUtils.closeQuietly(stream); } int scale = 1; if (options.outHeight > maxHeight || options.outWidth > maxWidth) { scale = Math.max(options.outHeight / maxHeight, options.outWidth / maxWidth); } bfOptions.inSampleSize = scale; }
44. Utils#cat()
Project: ceylon-compiler
File: Utils.java
File: Utils.java
public static void cat(File output, File... files) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(output); bos = new BufferedOutputStream(fos); for (File x : files) { FileInputStream fis = new FileInputStream(x); bis = new BufferedInputStream(fis); copyStream(bis, bos); Utils.close(bis); } } finally { Utils.close(bis); Utils.close(bos); Utils.close(fos); } }
45. T6836682#computeCRC()
Project: ceylon-compiler
File: T6836682.java
File: T6836682.java
static long computeCRC(File inFile) throws IOException { byte[] buffer = new byte[8192]; CRC32 crc = new CRC32(); FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(inFile); bis = new BufferedInputStream(fis); int n = bis.read(buffer); while (n > 0) { crc.update(buffer, 0, n); n = bis.read(buffer); } } finally { Utils.close(bis); Utils.close(fis); } return crc.getValue(); }
46. Utils#cat()
Project: ceylon
File: Utils.java
File: Utils.java
public static void cat(File output, File... files) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; FileOutputStream fos = null; try { fos = new FileOutputStream(output); bos = new BufferedOutputStream(fos); for (File x : files) { FileInputStream fis = new FileInputStream(x); bis = new BufferedInputStream(fis); copyStream(bis, bos); Utils.close(bis); } } finally { Utils.close(bis); Utils.close(bos); Utils.close(fos); } }
47. T6836682#computeCRC()
Project: ceylon
File: T6836682.java
File: T6836682.java
static long computeCRC(File inFile) throws IOException { byte[] buffer = new byte[8192]; CRC32 crc = new CRC32(); FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(inFile); bis = new BufferedInputStream(fis); int n = bis.read(buffer); while (n > 0) { crc.update(buffer, 0, n); n = bis.read(buffer); } } finally { Utils.close(bis); Utils.close(fis); } return crc.getValue(); }
48. Profiles#read()
Project: ceylon
File: Profiles.java
File: Profiles.java
public static Profiles read(File file) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); try { Properties p = new Properties(); p.load(in); if (p.containsKey("java/lang/Object")) return new SimpleProfiles(p); else return new MakefileProfiles(p); } finally { in.close(); } }
49. AbstractResourceBasedServiceRegistryDao#loadRegisteredServiceFromFile()
Project: cas
File: AbstractResourceBasedServiceRegistryDao.java
File: AbstractResourceBasedServiceRegistryDao.java
/** * Load registered service from file. * * @param file the file * @return the registered service, or null if file cannot be read, is not found, is empty or parsing error occurs. */ public RegisteredService loadRegisteredServiceFromFile(final File file) { if (!file.canRead()) { LOGGER.warn("[{}] is not readable. Check file permissions", file.getName()); return null; } if (!file.exists()) { LOGGER.warn("[{}] is not found at the path specified", file.getName()); return null; } if (file.length() == 0) { LOGGER.debug("[{}] appears to be empty so no service definition will be loaded", file.getName()); return null; } try (final BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) { return this.registeredServiceSerializer.from(in); } catch (final Exception e) { LOGGER.error("Error reading configuration file {}", file.getName(), e); } return null; }
50. BufferedFileDataInput#seek()
Project: canal
File: BufferedFileDataInput.java
File: BufferedFileDataInput.java
public void seek(long seekBytes) throws FileNotFoundException, IOException, InterruptedException { fileInput = new FileInputStream(file); fileChannel = fileInput.getChannel(); try { fileChannel.position(seekBytes); } catch (ClosedByInterruptException e) { throw new InterruptedException(); } bufferedInput = new BufferedInputStream(fileInput, size); dataInput = new DataInputStream(bufferedInput); offset = seekBytes; }
51. IoUtil#readFileAsString()
Project: camunda-bpm-platform
File: IoUtil.java
File: IoUtil.java
public static String readFileAsString(String filePath) { byte[] buffer = new byte[(int) getFile(filePath).length()]; BufferedInputStream inputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(getFile(filePath))); inputStream.read(buffer); } catch (Exception e) { throw LOG.exceptionWhileReadingFile(filePath, e); } finally { IoUtil.closeSilently(inputStream); } return new String(buffer, Charset.forName("UTF-8")); }
52. BarcodeDataFormat#readImage()
Project: camel
File: BarcodeDataFormat.java
File: BarcodeDataFormat.java
/** * Reads the message from a code. */ private String readImage(final Exchange exchange, final InputStream stream) throws Exception { final MultiFormatReader reader = new MultiFormatReader(); final BufferedInputStream in = exchange.getContext().getTypeConverter().mandatoryConvertTo(BufferedInputStream.class, stream); final BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(in)))); final Result result = reader.decode(bitmap, readerHintMap); // write the found barcode format into the header exchange.getOut().setHeader(Barcode.BARCODE_FORMAT, result.getBarcodeFormat()); return result.getText(); }
53. Activator#loadProperties()
Project: camel
File: Activator.java
File: Activator.java
protected static Properties loadProperties(URL url) { Properties properties = new Properties(); BufferedInputStream reader = null; try { reader = IOHelper.buffered(url.openStream()); properties.load(reader); } catch (IOException e) { throw new RuntimeException(e); } finally { IOHelper.close(reader, "properties", LOG); } return properties; }
54. DefaultFactoryFinder#doFindFactoryProperties()
Project: camel
File: DefaultFactoryFinder.java
File: DefaultFactoryFinder.java
private Properties doFindFactoryProperties(String key) throws IOException { String uri = path + key; InputStream in = classResolver.loadResourceAsStream(uri); if (in == null) { throw new NoFactoryAvailableException(uri); } // lets load the file BufferedInputStream reader = null; try { reader = IOHelper.buffered(in); Properties properties = new Properties(); properties.load(reader); return properties; } finally { IOHelper.close(reader, key, null); IOHelper.close(in, key, null); } }
55. ProtocolTest#buildACommand()
Project: cachecloud
File: ProtocolTest.java
File: ProtocolTest.java
@Test public void buildACommand() throws IOException { PipedInputStream pis = new PipedInputStream(); BufferedInputStream bis = new BufferedInputStream(pis); PipedOutputStream pos = new PipedOutputStream(pis); RedisOutputStream ros = new RedisOutputStream(pos); Protocol.sendCommand(ros, Protocol.Command.GET, "SOMEKEY".getBytes(Protocol.CHARSET)); ros.flush(); pos.close(); String expectedCommand = "*2\r\n$3\r\nGET\r\n$7\r\nSOMEKEY\r\n"; int b; StringBuilder sb = new StringBuilder(); while ((b = bis.read()) != -1) { sb.append((char) b); } assertEquals(expectedCommand, sb.toString()); }
56. AppleInfoPlistParsing#getBundleIdFromPlistStream()
Project: buck
File: AppleInfoPlistParsing.java
File: AppleInfoPlistParsing.java
/** * Extracts the bundle ID (CFBundleIdentifier) from an Info.plist, returning it if present. */ public static Optional<String> getBundleIdFromPlistStream(InputStream inputStream) throws IOException { NSDictionary infoPlist; try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) { try { infoPlist = (NSDictionary) PropertyListParser.parse(bufferedInputStream); } catch (Exception e) { throw new IOException(e); } } NSObject bundleId = infoPlist.objectForKey("CFBundleIdentifier"); if (bundleId == null) { return Optional.absent(); } else { return Optional.of(bundleId.toString()); } }
57. CheckpointManager#checkpoint()
Project: bitcoinj
File: CheckpointManager.java
File: CheckpointManager.java
/** * <p>Convenience method that creates a CheckpointManager, loads the given data, gets the checkpoint for the given * time, then inserts it into the store and sets that to be the chain head. Useful when you have just created * a new store from scratch and want to use configure it all in one go.</p> * * <p>Note that time is adjusted backwards by a week to account for possible clock drift in the block headers.</p> */ public static void checkpoint(NetworkParameters params, InputStream checkpoints, BlockStore store, long time) throws IOException, BlockStoreException { checkNotNull(params); checkNotNull(store); checkArgument(!(store instanceof FullPrunedBlockStore), "You cannot use checkpointing with a full store."); time -= 86400 * 7; checkArgument(time > 0); log.info("Attempting to initialize a new block store with a checkpoint for time {} ({})", time, Utils.dateTimeFormat(time * 1000)); BufferedInputStream stream = new BufferedInputStream(checkpoints); CheckpointManager manager = new CheckpointManager(params, stream); StoredBlock checkpoint = manager.getCheckpointBefore(time); store.put(checkpoint); store.setChainHead(checkpoint); }
58. PigTests#getLinesFromFile()
Project: bigtop
File: PigTests.java
File: PigTests.java
/** * Gets the lines from a given file. * * @param relativeFilePath The path relative to the datafu-tests project. * @return The lines from the file * @throws IOException */ protected String[] getLinesFromFile(String relativeFilePath) throws IOException { // assume that the working directory is the datafu-tests project File file = new File(System.getProperty("user.dir"), relativeFilePath).getAbsoluteFile(); BufferedInputStream content = new BufferedInputStream(new FileInputStream(file)); Object[] lines = IOUtils.readLines(content).toArray(); String[] result = new String[lines.length]; for (int i = 0; i < lines.length; i++) { result[i] = (String) lines[i]; } return result; }
59. CertificateFactory#engineGenerateCRLs()
Project: bc-java
File: CertificateFactory.java
File: CertificateFactory.java
/** * Returns a (possibly empty) collection view of the CRLs read from * the given input stream inStream. * * The inStream may contain a sequence of DER-encoded CRLs, or * a PKCS#7 CRL set. This is a PKCS#7 SignedData object, with the * only signficant field being crls. In particular the signature * and the contents are ignored. */ public Collection engineGenerateCRLs(InputStream inStream) throws CRLException { CRL crl; List crls = new ArrayList(); BufferedInputStream in = new BufferedInputStream(inStream); while ((crl = engineGenerateCRL(in)) != null) { crls.add(crl); } return crls; }
60. CertificateFactory#engineGenerateCertificates()
Project: bc-java
File: CertificateFactory.java
File: CertificateFactory.java
/** * Returns a (possibly empty) collection view of the certificates * read from the given input stream inStream. */ public Collection engineGenerateCertificates(InputStream inStream) throws CertificateException { java.security.cert.Certificate cert; BufferedInputStream in = new BufferedInputStream(inStream); List certs = new ArrayList(); while ((cert = engineGenerateCertificate(in)) != null) { certs.add(cert); } return certs; }
61. DependencyModule#collectDependenciesFromArtifact()
Project: bazel
File: DependencyModule.java
File: DependencyModule.java
/** * Updates {@link #requiredClasspath} to include dependencies from the given output artifact. */ private void collectDependenciesFromArtifact(String path) throws IOException { try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path))) { Deps.Dependencies deps = Deps.Dependencies.parseFrom(bis); // Sanity check to make sure we have a valid proto. if (!deps.hasRuleLabel()) { throw new IOException("Could not parse Deps.Dependencies message from proto."); } for (Deps.Dependency dep : deps.getDependencyList()) { if (dep.getKind() == Kind.EXPLICIT || dep.getKind() == Kind.IMPLICIT) { requiredClasspath.add(dep.getPath()); } } } catch (IOException e) { throw new IOException(String.format("error reading deps artifact: %s", path), e); } }
62. RemoteCommandUtils#drainInputStream()
Project: aws-toolkit-eclipse
File: RemoteCommandUtils.java
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)); } } }
63. DeploymentInitiator#loadFile()
Project: aws-sdk-java
File: DeploymentInitiator.java
File: DeploymentInitiator.java
public static String loadFile(String fileName) throws IOException { int length = (int) new File(fileName).length(); byte[] buffer = new byte[length]; BufferedInputStream is = null; try { is = new BufferedInputStream(new FileInputStream(fileName)); is.read(buffer); } finally { if (is != null) { is.close(); } } return new String(buffer); }
64. TreeHashGenerator#computeSHA256Hash()
Project: aws-sdk-java
File: TreeHashGenerator.java
File: TreeHashGenerator.java
private static byte[] computeSHA256Hash(byte[] data) throws NoSuchAlgorithmException, IOException { BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(data)); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] buffer = new byte[16384]; int bytesRead = -1; while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) { messageDigest.update(buffer, 0, bytesRead); } return messageDigest.digest(); } finally { try { bis.close(); } catch (Exception e) { } } }
65. Md5Utils#computeMD5Hash()
Project: aws-sdk-java
File: Md5Utils.java
File: Md5Utils.java
/** * Computes the MD5 hash of the data in the given input stream and returns * it as an array of bytes. * Note this method closes the given input stream upon completion. */ public static byte[] computeMD5Hash(InputStream is) throws IOException { BufferedInputStream bis = new BufferedInputStream(is); try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[SIXTEEN_K]; int bytesRead; while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) { messageDigest.update(buffer, 0, bytesRead); } return messageDigest.digest(); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } finally { try { bis.close(); } catch (Exception e) { LogFactory.getLog(Md5Utils.class).debug("Unable to close input stream of hash candidate: " + e); } } }
66. PlatformUtil#canReadDrive()
Project: autopsy
File: PlatformUtil.java
File: PlatformUtil.java
/** * Are we able to read this drive? Usually related to admin permissions. * * For all drives and partitions, we are using Java's ability to read the * first byte of a drive to determine if TSK would be able to read the drive * during the add image process. This returns whether the drive is readable * or not far faster than validating if TSK can open the drive. We are * assuming the results are almost exactly the same. * * @param diskPath path to the disk we want to read * * @return true if we successfully read the first byte * * @throws IOException if we fail to read */ private static boolean canReadDrive(String diskPath) { BufferedInputStream br = null; try { File tmp = new File(diskPath); br = new BufferedInputStream(new FileInputStream(tmp)); int b = br.read(); return b != -1; } catch (IOException ex) { return false; } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { } } }
67. Case#driveExists()
Project: autopsy
File: Case.java
File: Case.java
/** * Does the given drive path exist? * * @param path to drive * * @return true if the drive exists, false otherwise */ static boolean driveExists(String path) { // Test the drive by reading the first byte and checking if it's -1 BufferedInputStream br = null; try { File tmp = new File(path); br = new BufferedInputStream(new FileInputStream(tmp)); int b = br.read(); return b != -1; } catch (Exception ex) { return false; } finally { try { if (br != null) { br.close(); } } catch (IOException ex) { } } }
68. BitmapHelper#fetchAndRescaleBitmap()
Project: android-UniversalMusicPlayer
File: BitmapHelper.java
File: BitmapHelper.java
@SuppressWarnings("SameParameterValue") public static Bitmap fetchAndRescaleBitmap(String uri, int width, int height) throws IOException { URL url = new URL(uri); BufferedInputStream is = null; try { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); is = new BufferedInputStream(urlConnection.getInputStream()); is.mark(MAX_READ_LIMIT_PER_IMG); int scaleFactor = findScaleFactor(width, height, is); LogHelper.d(TAG, "Scaling bitmap ", uri, " by factor ", scaleFactor, " to support ", width, "x", height, "requested dimension"); is.reset(); return scaleBitmap(scaleFactor, is); } finally { if (is != null) { is.close(); } } }
69. ImageLoader#downloadBitmapFromUrl()
Project: android-art-res
File: ImageLoader.java
File: ImageLoader.java
private Bitmap downloadBitmapFromUrl(String urlString) { Bitmap bitmap = null; HttpURLConnection urlConnection = null; BufferedInputStream in = null; try { final URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE); bitmap = BitmapFactory.decodeStream(in); } catch (final IOException e) { Log.e(TAG, "Error in downloadBitmap: " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } MyUtils.close(in); } return bitmap; }
70. ZipExtractTask#unzipEntry1()
Project: AmazeFileManager
File: ZipExtractTask.java
File: ZipExtractTask.java
private void unzipEntry1(ZipFile zipfile, ZipEntry entry, String outputDir) throws IOException { output = new File(outputDir, fileName); BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(output)); try { int len; byte buf[] = new byte[1024]; while ((len = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, len); } } finally { outputStream.close(); inputStream.close(); } }
71. MyProxyLogon#connect()
Project: airavata
File: MyProxyLogon.java
File: MyProxyLogon.java
/** * Connects to the MyProxy server at the desired host and port. Requires * host authentication via SSL. The host's certificate subject must * match the requested hostname. If CA certificates are found in the * standard GSI locations, they will be used to verify the server's * certificate. If trust roots are requested and no CA certificates are * found, the server's certificate will still be accepted. */ public void connect() throws IOException, GeneralSecurityException { SSLContext sc = SSLContext.getInstance("SSL"); if (trustManager == null) { throw new IllegalStateException("No trust manager has been set!"); } TrustManager[] trustAllCerts = new TrustManager[] { trustManager }; sc.init(getKeyManagers(), trustAllCerts, new java.security.SecureRandom()); SSLSocketFactory sf = sc.getSocketFactory(); socket = (SSLSocket) sf.createSocket(host, port); socket.startHandshake(); socketIn = new BufferedInputStream(socket.getInputStream()); socketOut = new BufferedOutputStream(socket.getOutputStream()); state = State.CONNECTED; }
72. IOUtils#readAll()
Project: actor-platform
File: IOUtils.java
File: IOUtils.java
public static byte[] readAll(InputStream in, ProgressListener listener) throws IOException { BufferedInputStream bufferedInputStream = new BufferedInputStream(in); ByteArrayOutputStream os = new ByteArrayOutputStream(4096); byte[] buffer = buffers.get(); int len; int readed = 0; try { while ((len = bufferedInputStream.read(buffer)) >= 0) { Thread.yield(); os.write(buffer, 0, len); readed += len; if (listener != null) { listener.onProgress(readed); } } } catch (IOException e) { } return os.toByteArray(); }
73. BridgeTest#createLargeMessage()
Project: activemq-artemis
File: BridgeTest.java
File: BridgeTest.java
private ClientMessage createLargeMessage(ClientSession session, long largeMessageSize) throws Exception { File fileInput = new File(getTemporaryDir(), "huge_message_to_send.dat"); createFile(fileInput, largeMessageSize); System.out.println("File created at: " + fileInput.getAbsolutePath()); ClientMessage message = session.createMessage(ClientMessage.BYTES_TYPE, true); FileInputStream fileInputStream = new FileInputStream(fileInput); BufferedInputStream bufferedInput = new BufferedInputStream(fileInputStream); message.setBodyInputStream(bufferedInput); return message; }
74. TestUtil#unzip()
Project: lucene-solr
File: TestUtil.java
File: TestUtil.java
/** * Convenience method unzipping zipName into destDir. You must pass it a clean destDir. * * Closes the given InputStream after extracting! */ public static void unzip(InputStream in, Path destDir) throws IOException { in = new BufferedInputStream(in); try (ZipInputStream zipInput = new ZipInputStream(in)) { ZipEntry entry; byte[] buffer = new byte[8192]; while ((entry = zipInput.getNextEntry()) != null) { Path targetFile = destDir.resolve(entry.getName()); // be on the safe side: do not rely on that directories are always extracted // before their children (although this makes sense, but is it guaranteed?) Files.createDirectories(targetFile.getParent()); if (!entry.isDirectory()) { OutputStream out = Files.newOutputStream(targetFile); int len; while ((len = zipInput.read(buffer)) >= 0) { out.write(buffer, 0, len); } out.close(); } zipInput.closeEntry(); } } }
75. FileCopier#copyLegacy()
Project: zaproxy
File: FileCopier.java
File: FileCopier.java
public void copyLegacy(File in, File out) throws IOException { // CHECKSTYLE:OFF Inner assignments for try-with-resource are okay try (FileInputStream inStream = new FileInputStream(in); BufferedInputStream inBuf = new BufferedInputStream(inStream); FileOutputStream outStream = new FileOutputStream(out); BufferedOutputStream outBuf = new BufferedOutputStream(outStream)) { // CHECKSTYLE:ON byte[] buf = new byte[10240]; int len = 1; while (len > 0) { len = inBuf.read(buf); if (len > 0) { outBuf.write(buf, 0, len); } } } }
76. GettextAdapter#parseTranslationFile()
Project: zanata-server
File: GettextAdapter.java
File: GettextAdapter.java
@Override public TranslationsResource parseTranslationFile(URI fileUri, LocaleId sourceLocaleId, String localeId, Optional<String> params) throws FileFormatAdapterException, IllegalArgumentException { if (StringUtils.isEmpty(localeId)) { throw new IllegalArgumentException("locale id string cannot be null or empty"); } PoReader2 reader = new PoReader2(); BufferedInputStream inputStream = readStream(fileUri); TranslationsResource resource = reader.extractTarget(new InputSource(inputStream)); try { inputStream.close(); } catch (IOException e) { } return resource; }
77. GettextAdapter#parseDocumentFile()
Project: zanata-server
File: GettextAdapter.java
File: GettextAdapter.java
@Override public Resource parseDocumentFile(URI fileUri, LocaleId sourceLocale, Optional<String> params) throws FileFormatAdapterException, IllegalArgumentException { if (sourceLocale == null) { throw new IllegalArgumentException("Source locale cannot be null"); } if (fileUri == null) { throw new IllegalArgumentException("Document URI cannot be null"); } PoReader2 reader = new PoReader2(); BufferedInputStream inputStream = readStream(fileUri); Resource doc = reader.extractTemplate(new InputSource(inputStream), sourceLocale, ""); try { inputStream.close(); } catch (IOException e) { } return doc; }
78. GenericPropertiesAdapter#parseTranslationFile()
Project: zanata-server
File: GenericPropertiesAdapter.java
File: GenericPropertiesAdapter.java
@Override public TranslationsResource parseTranslationFile(URI fileUri, LocaleId sourceLocaleId, String localeId, Optional<String> params) throws FileFormatAdapterException, IllegalArgumentException { PropReader propReader = new PropReader(charset, sourceLocaleId, ContentState.Approved); /** * Resource is not needed for properties file translation parser as its * only used for contentHash check */ Resource srcDoc = new Resource(); TranslationsResource targetDoc = new TranslationsResource(); try (BufferedInputStream inputStream = readStream(fileUri)) { propReader.extractTarget(targetDoc, inputStream, srcDoc); } catch (IOException e) { throw new FileFormatAdapterException("Could not open the URL. The URL is OK but the input stream could not be opened.\n" + e.getMessage(), e); } return targetDoc; }
79. Files#copy()
Project: wicket
File: Files.java
File: Files.java
/** * make a copy of a file * * @param sourceFile * source file that needs to be cloned * @param targetFile * target file that should be a duplicate of source file * @throws IOException * if something went wrong */ public static void copy(final File sourceFile, final File targetFile) throws IOException { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(sourceFile)); out = new BufferedOutputStream(new FileOutputStream(targetFile)); IOUtils.copy(in, out); } finally { try { IOUtils.close(in); } finally { IOUtils.close(out); } } }
80. Utility#copyFile()
Project: weiciyuan
File: Utility.java
File: Utility.java
public static void copyFile(InputStream in, File destFile) throws IOException { BufferedInputStream bufferedInputStream = new BufferedInputStream(in); FileOutputStream outputStream = new FileOutputStream(destFile); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); byte[] buffer = new byte[1024]; int len; while ((len = bufferedInputStream.read(buffer)) != -1) { bufferedOutputStream.write(buffer, 0, len); } closeSilently(bufferedInputStream); closeSilently(bufferedOutputStream); }
81. FileManager#copyFile()
Project: weiciyuan
File: FileManager.java
File: FileManager.java
private static void copyFile(File sourceFile, File targetFile) throws IOException { BufferedInputStream inBuff = null; BufferedOutputStream outBuff = null; try { inBuff = new BufferedInputStream(new FileInputStream(sourceFile)); outBuff = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] b = new byte[1024 * 5]; int len; while ((len = inBuff.read(b)) != -1) { outBuff.write(b, 0, len); } outBuff.flush(); } finally { if (inBuff != null) { inBuff.close(); } if (outBuff != null) { outBuff.close(); } } }
82. InMemoryJarfile#put()
Project: voltdb
File: InMemoryJarfile.java
File: InMemoryJarfile.java
public byte[] put(String key, File value) throws IOException { byte[] bytes = null; int bytesRead = 0; bytes = new byte[(int) value.length()]; BufferedInputStream in = new BufferedInputStream(new FileInputStream(value)); try { bytesRead = in.read(bytes); } finally { in.close(); } assert (bytesRead != -1); return put(key, bytes); }
83. ShellTools#local_cmd()
Project: voltdb
File: ShellTools.java
File: ShellTools.java
public static String local_cmd(String[] command) { StringBuilder retval = new StringBuilder(); Process p = createProcess(command); if (p == null) { return null; } BufferedInputStream in = new BufferedInputStream(p.getInputStream()); int c; try { while ((c = in.read()) != -1) { retval.append((char) c); } } catch (Exception e) { p.destroy(); } try { p.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } p.destroy(); return retval.toString(); }
84. VersionChecker#downloadRemoteJarFile()
Project: VoipStorm
File: VersionChecker.java
File: VersionChecker.java
/** * * @return * @throws MalformedURLException * @throws IOException */ public final int downloadRemoteJarFile() throws java.net.MalformedURLException, java.io.IOException { // true = logtoapplic, true = logtofile eCallCenterManager.showStatus("Download and Check Update...", true, true); final URL remoteURL = new URL(UPDATEURL); HttpURLConnection urlConnection = (HttpURLConnection) remoteURL.openConnection(); // URLConnection urlConnection = remoteURL.openConnection(); urlConnection.setConnectTimeout(httpConTimeout); int responseCode = urlConnection.getResponseCode(); responseCodeDescription = urlConnection.getResponseMessage(); InputStream inputStream = urlConnection.getInputStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); FileOutputStream fileOutputStream = new FileOutputStream(newJarFileString); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); int byteNumber; while ((byteNumber = bufferedInputStream.read()) != -1) { // eCallCenterManager.showStatus("Downloading and checking Version..." + Integer.toString(bufferedInputStream.read()), true); bufferedOutputStream.write(byteNumber); } bufferedOutputStream.flush(); return responseCode; }
85. FileUtils#readFile()
Project: undertow
File: FileUtils.java
File: FileUtils.java
public static String readFile(InputStream file) { try (BufferedInputStream stream = new BufferedInputStream(file)) { byte[] buff = new byte[1024]; StringBuilder builder = new StringBuilder(); int read; while ((read = stream.read(buff)) != -1) { builder.append(new String(buff, 0, read)); } return builder.toString(); } catch (IOException e) { throw new RuntimeException(e); } }
86. InnerSocketThread#read()
Project: TProfiler
File: InnerSocketThread.java
File: InnerSocketThread.java
/** * ????? * * @param in * @return * @throws IOException */ private String read(InputStream in) throws IOException { BufferedInputStream bin = new BufferedInputStream(in); StringBuffer sb = new StringBuffer(); int i; while ((i = bin.read()) != -1) { char c = (char) i; if (c == '\r') { break; } else { sb.append(c); } } return sb.toString(); }
87. TProfilerClient#read()
Project: TProfiler
File: TProfilerClient.java
File: TProfilerClient.java
/** * ????? * * @param in * @return * @throws IOException */ private static String read(InputStream in) throws IOException { BufferedInputStream bin = new BufferedInputStream(in); StringBuffer sb = new StringBuffer(); int i; while ((i = bin.read()) != -1) { char c = (char) i; if (c == '\r') { break; } else { sb.append(c); } } return sb.toString(); }
88. SimpleTransportHandler#initialize()
Project: TLS-Attacker
File: SimpleTransportHandler.java
File: SimpleTransportHandler.java
@Override public void initialize(String address, int port) throws IOException { if (address.equals("server")) { serverSocket = new ServerSocket(port); socket = serverSocket.accept(); LOGGER.debug("Server"); isServer = true; } else { socket = new Socket(address, port); } OutputStream os = socket.getOutputStream(); bos = new BufferedOutputStream(os); InputStream is = socket.getInputStream(); bis = new BufferedInputStream(is); }
89. DOMCreateUtils#parseFile()
Project: team-explorer-everywhere
File: DOMCreateUtils.java
File: DOMCreateUtils.java
/** * Parses the specified {@link File} into a {@link Document}. * * @throws XMLException * if parsing the {@link File} fails * * @param builder * the {@link DocumentBuilder} to parse with, or <code>null</code> to * use a {@link DocumentBuilder} from the internal pool * @param file * a {@link File} containing XML to parse (must not be * <code>null</code>) * @param encoding * the encoding of the {@link File}, or <code>null</code> if the * encoding is not known (passing <code>null</code> is not * recommended) * @return a new {@link Document} (never <code>null</code>) */ public static Document parseFile(final DocumentBuilder builder, final File file, final String encoding) { //$NON-NLS-1$ Check.notNull(file, "file"); InputStream inputStream; try { inputStream = new FileInputStream(file); } catch (final FileNotFoundException e) { throw new XMLException(e); } inputStream = new BufferedInputStream(inputStream); return parseStream(builder, inputStream, encoding, NONE); }
90. HTMLIncludeHelper#readInputStreamToBase64()
Project: team-explorer-everywhere
File: HTMLIncludeHelper.java
File: HTMLIncludeHelper.java
/** * Read the given {@link InputStream}, returning it as base64 encoded * representation of the resource. * * @param inputStream * The input stream to encode as base64 * @return The base64 encoded data. * @throws IOException * If the given resource, or any included resources, could not be * read */ private String readInputStreamToBase64(final InputStream inputStream) throws IOException { //$NON-NLS-1$ Check.notNull(inputStream, "inputStream"); final BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int b; while ((b = bufferedStream.read()) >= 0) { byteStream.write(b); } //$NON-NLS-1$ return new String(Base64.encodeBase64(byteStream.toByteArray()), "US-ASCII"); }
91. UncompressUtils#uncompressTarArchive()
Project: Symfony-2-Eclipse-Plugin
File: UncompressUtils.java
File: UncompressUtils.java
/** * Uncompress all entries found in a tar archive file into the given output * directory. Entry names are translated using the translator before being * put on the file system. * * @param archiveFile The tar archive file to uncompress * @param outputDirectory The output directory where to put uncompressed entries * @param entryNameTranslator The entry name translator to use * * @throws IOException When an error occurs while uncompressing the tar archive */ public static void uncompressTarArchive(File archiveFile, File outputDirectory, EntryNameTranslator entryNameTranslator) throws IOException { FileInputStream fileInputStream = new FileInputStream(archiveFile); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); TarArchiveInputStream tarInputStream = new TarArchiveInputStream(bufferedInputStream); try { TarArchiveEntry tarEntry = null; while ((tarEntry = tarInputStream.getNextTarEntry()) != null) { uncompressTarArchiveEntry(tarInputStream, tarEntry, outputDirectory, entryNameTranslator); } } finally { tarInputStream.close(); } }
92. FileUtils#readFileAsString()
Project: java-koans
File: FileUtils.java
File: FileUtils.java
public static String readFileAsString(File file) { byte[] buffer = new byte[(int) file.length()]; BufferedInputStream f = null; try { f = new BufferedInputStream(new FileInputStream(file)); f.read(buffer); } catch (IOException e) { throw new RuntimeException(e); } finally { if (f != null) try { f.close(); } catch (IOException ignored) { } } return new String(buffer); }
93. FileUtils#addFileToJar()
Project: jadx
File: FileUtils.java
File: FileUtils.java
public static void addFileToJar(JarOutputStream jar, File source, String entryName) throws IOException { BufferedInputStream in = null; try { JarEntry entry = new JarEntry(entryName); entry.setTime(source.lastModified()); jar.putNextEntry(entry); in = new BufferedInputStream(new FileInputStream(source)); copyStream(in, jar); jar.closeEntry(); } finally { close(in); } }
94. ImportXmlFromInputStream#execute()
Project: jackrabbit
File: ImportXmlFromInputStream.java
File: ImportXmlFromInputStream.java
/** * {@inheritDoc} */ public boolean execute(Context ctx) throws Exception { InputStream is = (InputStream) ctx.get(this.inputStreamKey); String dest = (String) ctx.get(this.destJcrPathKey); String persistent = (String) ctx.get(this.persistentKey); int uuidBehaviour = Integer.valueOf((String) ctx.get(this.uuidBehaviourKey)).intValue(); BufferedInputStream bis = new BufferedInputStream(is); Session s = CommandHelper.getSession(ctx); Node n = CommandHelper.getNode(ctx, dest); if (persistent != null && Boolean.valueOf(persistent).equals(Boolean.TRUE)) { s.getWorkspace().importXML(n.getPath(), bis, uuidBehaviour); } else { s.importXML(n.getPath(), bis, uuidBehaviour); } return false; }
95. AbstractImportXmlTest#importXML()
Project: jackrabbit
File: AbstractImportXmlTest.java
File: AbstractImportXmlTest.java
/** * Imports a given document using either Workspace.importXML or * Session.importXML method. * * @param absPath the absPath to the parent node where to import the * document * @param document the document to import * @param uuidBehaviour how the uuid collisions should be handled * @param withWorkspace if workspace or session interface should be used * @throws RepositoryException * @throws IOException */ protected void importXML(String absPath, Document document, int uuidBehaviour, boolean withWorkspace) throws RepositoryException, IOException { serialize(document); BufferedInputStream bin = new BufferedInputStream(new FileInputStream(file)); try { if (withWorkspace) { workspace.importXML(absPath, bin, uuidBehaviour); } else { session.importXML(absPath, bin, uuidBehaviour); session.save(); } } finally { try { bin.close(); } catch (IOException ignore) { } } }
96. FileUtil#copyFile()
Project: jabref
File: FileUtil.java
File: FileUtil.java
/** * Copies a file. * * @param source File Source file * @param dest File Destination file * @param deleteIfExists boolean Determines whether the copy goes on even if the file * exists. * @return boolean Whether the copy succeeded, or was stopped due to the * file already existing. * @throws IOException */ public static boolean copyFile(File source, File dest, boolean deleteIfExists) throws IOException { // Check if the file already exists. if (dest.exists() && !deleteIfExists) { return false; } try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest))) { int el; while ((el = in.read()) >= 0) { out.write(el); } out.flush(); } return true; }
97. OpenOfficeDocumentCreator#exportOpenOfficeCalc()
Project: jabref
File: OpenOfficeDocumentCreator.java
File: OpenOfficeDocumentCreator.java
private static void exportOpenOfficeCalc(File file, BibDatabase database, List<BibEntry> entries) throws Exception { // First store the xml formatted content to a temporary file. File tmpFile = File.createTempFile("oocalc", null); OpenOfficeDocumentCreator.exportOpenOfficeCalcXML(tmpFile, database, entries); // Then add the content to the zip file: try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile))) { OpenOfficeDocumentCreator.storeOpenOfficeFile(file, in); } // Delete the temporary file: if (!tmpFile.delete()) { LOGGER.info("Cannot delete temporary export file"); } }
98. OpenDocumentSpreadsheetCreator#exportOpenDocumentSpreadsheet()
Project: jabref
File: OpenDocumentSpreadsheetCreator.java
File: OpenDocumentSpreadsheetCreator.java
private static void exportOpenDocumentSpreadsheet(File file, BibDatabase database, List<BibEntry> entries) throws Exception { // First store the xml formatted content to a temporary file. File tmpFile = File.createTempFile("opendocument", null); OpenDocumentSpreadsheetCreator.exportOpenDocumentSpreadsheetXML(tmpFile, database, entries); // Then add the content to the zip file: try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile))) { OpenDocumentSpreadsheetCreator.storeOpenDocumentSpreadsheetFile(file, in); } // Delete the temporary file: if (!tmpFile.delete()) { LOGGER.info("Cannot delete temporary export file"); } }
99. OldLineNumberInputStreamTest#setUp()
Project: j2objc
File: OldLineNumberInputStreamTest.java
File: OldLineNumberInputStreamTest.java
protected void setUp() { /* * In order for IOException to be thrown in reset(),the inputStream to * the constructor cannot be a byteArrayInputstream because the reset() * in byteArrayInputStream does not throw IOException. When * BufferedInputStream is used, the size of the buffer must be smaller * than the readlimit in mark inorder for IOException to be thrown */ BufferedInputStream buftemp = new BufferedInputStream(new ByteArrayInputStream(text.getBytes()), 4); lnis = new LineNumberInputStream(buftemp); lnis2 = new LineNumberInputStream(new ByteArrayInputStream(dosText.getBytes())); }
100. OldBufferedInputStreamTest#setUp()
Project: j2objc
File: OldBufferedInputStreamTest.java
File: OldBufferedInputStreamTest.java
@Override protected void setUp() throws IOException { fileName = System.getProperty("user.dir"); String separator = System.getProperty("file.separator"); if (fileName.charAt(fileName.length() - 1) == separator.charAt(0)) { fileName = Support_PlatformFile.getNewPlatformFile(fileName, "input.tst"); } else { fileName = Support_PlatformFile.getNewPlatformFile(fileName + separator, "input.tst"); } OutputStream fos = new FileOutputStream(fileName); fos.write(fileString.getBytes()); fos.close(); isFile = new FileInputStream(fileName); is = new BufferedInputStream(isFile); }