Here are the examples of the java api class java.io.BufferedOutputStream taken from open source projects.
1. TestJsonReader#drill_4032()
Project: drill
File: TestJsonReader.java
File: TestJsonReader.java
@Test public void drill_4032() throws Exception { String dfs_temp = getDfsTestTmpSchemaLocation(); File table_dir = new File(dfs_temp, "drill_4032"); table_dir.mkdir(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "a.json"))); os.write("{\"col1\": \"val1\",\"col2\": null}".getBytes()); os.write("{\"col1\": \"val1\",\"col2\": {\"col3\":\"abc\", \"col4\":\"xyz\"}}".getBytes()); os.flush(); os.close(); os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "b.json"))); os.write("{\"col1\": \"val1\",\"col2\": null}".getBytes()); os.write("{\"col1\": \"val1\",\"col2\": null}".getBytes()); os.flush(); os.close(); testNoResult("select t.col2.col3 from dfs_test.tmp.drill_4032 t"); }
2. TestJavaBinCodec#genBinaryFiles()
Project: lucene-solr
File: TestJavaBinCodec.java
File: TestJavaBinCodec.java
public void genBinaryFiles() throws IOException { JavaBinCodec javabin = new JavaBinCodec(); ByteArrayOutputStream os = new ByteArrayOutputStream(); Object data = generateAllDataTypes(); javabin.marshal(data, os); byte[] out = os.toByteArray(); FileOutputStream fs = new FileOutputStream(new File(BIN_FILE_LOCATION)); BufferedOutputStream bos = new BufferedOutputStream(fs); bos.write(out); bos.close(); //Binary file with child documents javabin = new JavaBinCodec(); SolrDocument sdoc = generateSolrDocumentWithChildDocs(); os = new ByteArrayOutputStream(); javabin.marshal(sdoc, os); fs = new FileOutputStream(new File(BIN_FILE_LOCATION_CHILD_DOCS)); bos = new BufferedOutputStream(fs); bos.write(os.toByteArray()); bos.close(); }
3. TestCsvHeader#testEmptyFinalColumn()
Project: drill
File: TestCsvHeader.java
File: TestCsvHeader.java
@Test public void testEmptyFinalColumn() throws Exception { String dfs_temp = getDfsTestTmpSchemaLocation(); File table_dir = new File(dfs_temp, "emptyFinalColumn"); table_dir.mkdir(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "a.csvh"))); os.write("field1,field2\n".getBytes()); for (int i = 0; i < 10000; i++) { os.write("a,\n".getBytes()); } os.flush(); os.close(); String query = "select * from dfs_test.tmp.emptyFinalColumn"; TestBuilder builder = testBuilder().sqlQuery(query).ordered().baselineColumns("field1", "field2"); for (int i = 0; i < 10000; i++) { builder.baselineValues("a", ""); } builder.go(); }
4. WebInterfaceImpl#saveStreamToFile()
Project: RoboSpock
File: WebInterfaceImpl.java
File: WebInterfaceImpl.java
public static void saveStreamToFile(final InputStream is, final File file) throws IOException { if (is == null) { throw new IOException("Empty stream"); } final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file)); final byte[] data = new byte[16384]; int n; while ((n = is.read(data, 0, data.length)) != -1) { os.write(data, 0, n); } os.flush(); os.close(); }
5. ExportFileSystem#createFile()
Project: jackrabbit
File: ExportFileSystem.java
File: ExportFileSystem.java
/** * Exports an nt:file to the file system * @param node * the <code>Node</code> * @param file * the <code>File</code> * @throws IOException * if an IOException occurs * @throws CommandException * if the <code>File</code> can't be created * @throws ValueFormatException * if a <code>Value</code> can't be retrieved * @throws PathNotFoundException * if the <code>Node</code> can't be found * @throws RepositoryException * if the current working <code>Repository</code> throws an * <code>Exception</code> */ private void createFile(Node node, File file) throws IOException, CommandException, ValueFormatException, PathNotFoundException, RepositoryException { boolean created = file.createNewFile(); if (!created) { throw new CommandException("exception.file.not.created", new String[] { file.getPath() }); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); InputStream in = node.getNode("jcr:content").getProperty("jcr:data").getStream(); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.flush(); out.close(); }
6. ModelCache#writeValueToDisk()
Project: ignition
File: ModelCache.java
File: ModelCache.java
/** * @see com.github.droidfu.cachefu.AbstractCache#writeValueToDisk(java.io.File, * java.lang.Object) */ @Override protected void writeValueToDisk(File file, CachedModel data) throws IOException { // Write object into parcel Parcel parcelOut = Parcel.obtain(); parcelOut.writeString(data.getClass().getCanonicalName()); parcelOut.writeParcelable(data, 0); // Write byte data to file FileOutputStream ostream = new FileOutputStream(file); BufferedOutputStream bistream = new BufferedOutputStream(ostream); bistream.write(parcelOut.marshall()); bistream.close(); }
7. LocalReadWritePerf#writeLocalFile()
Project: hadoop-20
File: LocalReadWritePerf.java
File: LocalReadWritePerf.java
/** * write a local dist file */ private void writeLocalFile(File filePath, long sizeKB) throws IOException { BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(filePath)); long fileSize = sizeKB * 1024; int bufSize = (int) Math.min(MAX_BUF_SIZE, fileSize); byte[] data = new byte[bufSize]; long toWrite = fileSize; rand.nextBytes(data); while (toWrite > 0) { int len = (int) Math.min(toWrite, bufSize); os.write(data, 0, len); toWrite -= len; } os.flush(); os.close(); }
8. ModelCache#writeValueToDisk()
Project: droid-fu
File: ModelCache.java
File: ModelCache.java
/** * @see com.github.droidfu.cachefu.AbstractCache#writeValueToDisk(java.io.File, * java.lang.Object) */ @Override protected void writeValueToDisk(File file, CachedModel data) throws IOException { // Write object into parcel Parcel parcelOut = Parcel.obtain(); parcelOut.writeString(data.getClass().getCanonicalName()); parcelOut.writeParcelable(data, 0); // Write byte data to file FileOutputStream ostream = new FileOutputStream(file); BufferedOutputStream bistream = new BufferedOutputStream(ostream); bistream.write(parcelOut.marshall()); bistream.close(); }
9. TestJsonReader#testSumMultipleBatches()
Project: drill
File: TestJsonReader.java
File: TestJsonReader.java
@Test public void testSumMultipleBatches() throws Exception { String dfs_temp = getDfsTestTmpSchemaLocation(); File table_dir = new File(dfs_temp, "multi_batch"); table_dir.mkdir(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "a.json"))); for (int i = 0; i < 10000; i++) { os.write("{ type : \"map\", data : { a : 1 } }\n".getBytes()); os.write("{ type : \"bigint\", data : 1 }\n".getBytes()); } os.flush(); os.close(); String query = "select sum(cast(case when `type` = 'map' then t.data.a else data end as bigint)) `sum` from dfs_test.tmp.multi_batch t"; try { testBuilder().sqlQuery(query).ordered().optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true").baselineColumns("sum").baselineValues(20000L).go(); } finally { testNoResult("alter session set `exec.enable_union_type` = false"); } }
10. TestProtobufTypeUtil#testSdcToProtobufUnknownFields()
Project: datacollector
File: TestProtobufTypeUtil.java
File: TestProtobufTypeUtil.java
@Test public void testSdcToProtobufUnknownFields() throws Exception { List<Record> protobufRecords = ProtobufTestUtil.getProtobufRecords(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(bOut); for (int i = 0; i < protobufRecords.size(); i++) { DynamicMessage dynamicMessage = ProtobufTypeUtil.sdcFieldToProtobufMsg(protobufRecords.get(i), md, typeToExtensionMap, defaultValueMap); dynamicMessage.writeDelimitedTo(bufferedOutputStream); } bufferedOutputStream.flush(); bufferedOutputStream.close(); ProtobufTestUtil.checkProtobufDataUnknownFields(bOut.toByteArray()); }
11. TestProtobufTypeUtil#testSdcToProtobufExtensions()
Project: datacollector
File: TestProtobufTypeUtil.java
File: TestProtobufTypeUtil.java
@Test public void testSdcToProtobufExtensions() throws Exception { List<Record> protobufRecords = ProtobufTestUtil.getProtobufRecords(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(bOut); for (int i = 0; i < protobufRecords.size(); i++) { DynamicMessage dynamicMessage = ProtobufTypeUtil.sdcFieldToProtobufMsg(protobufRecords.get(i), md, typeToExtensionMap, defaultValueMap); dynamicMessage.writeDelimitedTo(bufferedOutputStream); } bufferedOutputStream.flush(); bufferedOutputStream.close(); ProtobufTestUtil.checkProtobufDataExtensions(bOut.toByteArray()); }
12. TestProtobufTypeUtil#testSdcToProtobufFields()
Project: datacollector
File: TestProtobufTypeUtil.java
File: TestProtobufTypeUtil.java
@Test public void testSdcToProtobufFields() throws Exception { List<Record> protobufRecords = ProtobufTestUtil.getProtobufRecords(); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(bOut); for (int i = 0; i < protobufRecords.size(); i++) { DynamicMessage dynamicMessage = ProtobufTypeUtil.sdcFieldToProtobufMsg(protobufRecords.get(i), md, typeToExtensionMap, defaultValueMap); dynamicMessage.writeDelimitedTo(bufferedOutputStream); } bufferedOutputStream.flush(); bufferedOutputStream.close(); ProtobufTestUtil.checkProtobufDataFields(bOut.toByteArray()); }
13. 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; }
14. 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; }
15. UnzipUtils#extractFile()
Project: tomahawk-android
File: UnzipUtils.java
File: UnzipUtils.java
/** * Extracts a zip entry (file entry) */ private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException { File dir = new File(filePath).getParentFile(); boolean success = dir.mkdirs(); if (!success) { Log.e(TAG, "extractFile - Wasn't able to create directory: " + filePath); } BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); byte[] bytesIn = new byte[BUFFER_SIZE]; int read; while ((read = zipIn.read(bytesIn)) != -1) { bos.write(bytesIn, 0, read); } bos.close(); }
16. TestS3FileSystem#setup()
Project: Priam
File: TestS3FileSystem.java
File: TestS3FileSystem.java
@BeforeClass public static void setup() throws InterruptedException, IOException { new MockS3PartUploader(); new MockAmazonS3Client(); injector = Guice.createInjector(new BRTestModule()); File dir1 = new File("target/data/Keyspace1/Standard1/backups/201108082320"); if (!dir1.exists()) dir1.mkdirs(); File file = new File(FILE_PATH); long fiveKB = (5L * 1024); byte b = 8; BufferedOutputStream bos1 = new BufferedOutputStream(new FileOutputStream(file)); for (long i = 0; i < fiveKB; i++) { bos1.write(b); } bos1.close(); }
17. MetadataTestCase#getTestDataFile()
Project: oodt
File: MetadataTestCase.java
File: MetadataTestCase.java
/** * Get a named test data file. This will yield a test data file using the standard Java resource mechanism * (ie, fetching out of a jar, from the class path, etc.) and stick it in a temporary file, since the * metadata API works with files it can both name and use, not just streams of file data. * * @param name Name of the test data file to retrieve. * @return A {@link java.io.File} containing the named test dat. * @throws IOException If an I/O error occurs. */ public File getTestDataFile(String name) throws IOException { // Not found? Try resource stream InputStream in = MetadataTestCase.class.getResourceAsStream(name); if (// Still not found? Bummer. in == null) throw new IllegalArgumentException("Unknown test data file `" + name + "`; not found in resource path"); // What the tests want: Files. File fn = new File(tmpDir, name); // Copy data to it BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fn)); // Buffer for efficiency in = new BufferedInputStream(in); // Classic disk page size byte[] buf = new byte[512]; for (; ; ) { // For ever // Read into our buffer int c = in.read(buf); // EOF? Done. if (c == -1) break; // Not EOF? Copy out. out.write(buf, 0, c); } in.close(); out.close(); return fn; }
18. JarFileCopy#copy()
Project: LGame
File: JarFileCopy.java
File: JarFileCopy.java
public static long copy(InputStream in, OutputStream outstream) throws IOException { BufferedOutputStream out = new BufferedOutputStream(outstream); byte[] buf = new byte[1024 * 10]; long total = 0; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); total += len; } in.close(); out.close(); return total; }
19. GZIPcompress#main()
Project: java-core-learning-example
File: GZIPcompress.java
File: GZIPcompress.java
public static void main(String[] args) throws IOException { // ?Reader??? BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("data.gz"), "UTF-8")); // ??????????????? BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("data.gz"))); System.out.println("Writing File ??"); int c; while ((c = in.read()) > 0) out.write(String.valueOf((char) c).getBytes("UTF-8")); in.close(); out.close(); System.out.println("Reading File ??"); // ?????????? BufferedReader in2 = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("data.gz")), // encoding question "UTF-8")); String s; while ((s = in2.readLine()) != null) System.out.println(s); in2.close(); }
20. OldBufferedOutputStreamTest#test_flush()
Project: j2objc
File: OldBufferedOutputStreamTest.java
File: OldBufferedOutputStreamTest.java
public void test_flush() throws IOException { baos = new ByteArrayOutputStream(); os = new java.io.BufferedOutputStream(baos, 600); os.write(fileString.getBytes(), 0, 500); os.flush(); assertEquals("Test 1: Bytes not written after flush;", 500, ((ByteArrayOutputStream) baos).size()); os.close(); sos = new Support_OutputStream(true); os = new BufferedOutputStream(sos, 10); try { os.flush(); fail("Test 2: IOException expected."); } catch (IOException e) { } // To avoid exception during tearDown(). sos.setThrowsException(false); }
21. SimpleFieldSet#writeTo()
Project: fred
File: SimpleFieldSet.java
File: SimpleFieldSet.java
/** Write to the given OutputStream and flush it. */ public void writeTo(OutputStream os, int bufferSize) throws IOException { BufferedOutputStream bos = null; OutputStreamWriter osw = null; BufferedWriter bw = null; bos = new BufferedOutputStream(os, bufferSize); try { osw = new OutputStreamWriter(bos, "UTF-8"); } catch (UnsupportedEncodingException e) { Logger.error(SimpleFieldSet.class, "Impossible: " + e, e); throw e; } bw = new BufferedWriter(osw); writeTo(bw); bw.flush(); }
22. 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; }
23. StandardQuotaStrategyTest#createFileOfSize()
Project: community-edition
File: StandardQuotaStrategyTest.java
File: StandardQuotaStrategyTest.java
private File createFileOfSize(long sizeInKB) throws IOException { File file = new File(TempFileProvider.getSystemTempDir(), GUID.generate() + ".generated"); file.deleteOnExit(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file)); for (long i = 0; i < sizeInKB; i++) { os.write(aKB); } os.close(); return file; }
24. AbstractEmailTest#getMessageBodyBytes()
Project: commons-email
File: AbstractEmailTest.java
File: AbstractEmailTest.java
/** * Gets the byte making up the body of the message. * * @param mimeMessage * The mime message from which to extract the body. * @return A byte array representing the message body * @throws IOException * Thrown while serializing the body from * {@link DataHandler#writeTo(java.io.OutputStream)}. * @throws MessagingException * Thrown while getting the body content from * {@link MimeMessage#getDataHandler()} * @since 1.1 */ private byte[] getMessageBodyBytes(final MimeMessage mimeMessage) throws IOException, MessagingException { final DataHandler dataHandler = mimeMessage.getDataHandler(); final ByteArrayOutputStream byteArrayOutStream = new ByteArrayOutputStream(); final BufferedOutputStream buffOs = new BufferedOutputStream(byteArrayOutStream); dataHandler.writeTo(buffOs); buffOs.flush(); return byteArrayOutStream.toByteArray(); }
25. FileTools#writeToFile()
Project: CJFrameForAndroid
File: FileTools.java
File: FileTools.java
/** * ?????? * * @param dataIns * @param target * @throws java.io.IOException */ public static void writeToFile(InputStream dataIns, File target) throws IOException { final int BUFFER = 1024; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target)); int count; byte data[] = new byte[BUFFER]; while ((count = dataIns.read(data, 0, BUFFER)) != -1) { bos.write(data, 0, count); } bos.close(); }
26. system#decompress()
Project: AndroidQuickUtils
File: system.java
File: system.java
/** * Decompresses a zip file (source) that has a single zip entry. * * @param source * @param target * @throws IOException */ public static void decompress(File source, File target) throws IOException { ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(source), BUFFER)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target)); zipIn.getNextEntry(); byte data[] = new byte[BUFFER]; int count = 0; while ((count = zipIn.read(data, 0, BUFFER)) != -1) { bos.write(data, 0, count); } bos.close(); zipIn.close(); }
27. BridgeTest#createFile()
Project: activemq-artemis
File: BridgeTest.java
File: BridgeTest.java
private static void createFile(final File file, final long fileSize) throws IOException { if (file.exists()) { System.out.println("---file already there " + file.length()); return; } FileOutputStream fileOut = new FileOutputStream(file); BufferedOutputStream buffOut = new BufferedOutputStream(fileOut); byte[] outBuffer = new byte[1024 * 1024]; System.out.println(" --- creating file, size: " + fileSize); for (long i = 0; i < fileSize; i += outBuffer.length) { buffOut.write(outBuffer); } buffOut.close(); }
28. GnuPGContext#encryptToBinary()
Project: gnupg-for-android
File: GnuPGContext.java
File: GnuPGContext.java
/** * Encrypt plain data and return encrypted data in binary form. * * @param recipients array of keys to encrypt to * @param plain the GnuPGData to be encrypted * @return String encrypted data in ASCII-armored text */ public byte[] encryptToBinary(GnuPGKey[] recipients, GnuPGData plain) { long l = getInternalRepresentation(); boolean previous = gpgmeGetArmor(l); gpgmeSetArmor(l, true); GnuPGData cipher = createDataObject(); encrypt(recipients, plain, cipher); ByteArrayOutputStream baos = new ByteArrayOutputStream(plain.size()); BufferedOutputStream out = new BufferedOutputStream(baos, 8192); try { cipher.write(out); } catch (IOException e) { e.printStackTrace(); } cipher.destroy(); if (// maintain the original ASCII-Armor state previous == false) gpgmeSetArmor(l, false); return baos.toByteArray(); }
29. FileUploadServlet#readToFile()
Project: geronimo
File: FileUploadServlet.java
File: FileUploadServlet.java
private static void readToFile(DataInputStream in, File temp, int length) throws IOException { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(temp)); int total, read; try { byte[] buf = new byte[1024]; total = 0; while ((read = in.read(buf, 0, Math.min(buf.length, length - total))) > -1) { out.write(buf, 0, read); total += read; if (total == length) { break; } } } finally { try { out.flush(); } catch (IOException e) { } out.close(); } if (total != length) { throw new IOException("Unable to read entire upload file (" + total + "b expecting " + length + "b)"); } }
30. OptionPanel#saveOptionsToFile()
Project: freeplane
File: OptionPanel.java
File: OptionPanel.java
private void saveOptionsToFile() { final Properties properties = getOptionProperties(); if (!validate(properties)) return; JFileChooser fileChooser = getFileChooser(); final int status = fileChooser.showSaveDialog(topDialog); if (status != JFileChooser.APPROVE_OPTION) return; final File outputFile = getOutputFile(fileChooser); try (final BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(outputFile))) { properties.store(output, ""); } catch (Exception e) { LogUtils.warn(e); } }
31. IoUtil#writeStringToFile()
Project: fixflow
File: IoUtil.java
File: IoUtil.java
public static void writeStringToFile(String content, String filePath) { BufferedOutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(getFile(filePath))); outputStream.write(content.getBytes()); outputStream.flush(); } catch (Exception e) { throw new FixFlowException("Couldn't write file " + filePath, e); } finally { IoUtil.closeSilently(outputStream); } }
32. FileUtil#copyFile()
Project: fixflow
File: FileUtil.java
File: FileUtil.java
/** * ???? * @param from * @param target * @throws IOException */ public static void copyFile(InputStream from, String target) throws IOException { FileUtil.makeParent(target); BufferedInputStream input = new BufferedInputStream(from); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target)); try { byte[] buff = new byte[2048]; int size = 0; while ((size = input.read(buff)) != -1) { out.write(buff, 0, size); out.flush(); } } finally { input.close(); out.close(); } }
33. ImageHelper#writeToFile()
Project: fanfouapp-opensource
File: ImageHelper.java
File: ImageHelper.java
public static boolean writeToFile(final File file, final Bitmap bitmap) { if ((bitmap == null) || (file == null) || file.exists()) { return false; } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(file), ImageHelper.OUTPUT_BUFFER_SIZE); return bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); } catch (final IOException e) { if (AppContext.DEBUG) { Log.d(ImageHelper.TAG, "writeToFile:" + e.getMessage()); } } finally { IOHelper.forceClose(bos); } return false; }
34. IOHelpers#writeTo()
Project: fabric8
File: IOHelpers.java
File: IOHelpers.java
public static void writeTo(OutputStream outputStream, InputStream in, int bufferSize, boolean close) throws IOException { BufferedOutputStream out = new BufferedOutputStream(outputStream, bufferSize); BufferedInputStream bufferedIn = new BufferedInputStream(in, bufferSize); while (true) { int b = bufferedIn.read(); if (b >= 0) { out.write(b); } else { in.close(); if (close) { out.close(); } else { out.flush(); } return; } } }
35. FileSystemStorageManager#putObject()
Project: eucalyptus
File: FileSystemStorageManager.java
File: FileSystemStorageManager.java
public void putObject(String bucket, String object, byte[] base64Data, boolean append) throws IOException { File objectFile = new File(WalrusInfo.getWalrusInfo().getStorageDir() + FILE_SEPARATOR + bucket + FILE_SEPARATOR + object); if (!objectFile.exists()) { objectFile.createNewFile(); } BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(objectFile, append)); try { outputStream.write(base64Data); } catch (IOException ex) { LOG.error(ex); Logs.extreme().error(ex, ex); throw ex; } finally { try { outputStream.close(); } catch (IOException ex) { LOG.error(ex); } } }
36. Utils#cat()
Project: error-prone-javac
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); } }
37. DeflateCompressor#streamOutput()
Project: elasticsearch
File: DeflateCompressor.java
File: DeflateCompressor.java
@Override public StreamOutput streamOutput(StreamOutput out) throws IOException { out.writeBytes(HEADER); final boolean nowrap = true; final Deflater deflater = new Deflater(LEVEL, nowrap); final boolean syncFlush = true; OutputStream compressedOut = new DeflaterOutputStream(out, deflater, BUFFER_SIZE, syncFlush); compressedOut = new BufferedOutputStream(compressedOut, BUFFER_SIZE); return new OutputStreamStreamOutput(compressedOut) { final AtomicBoolean closed = new AtomicBoolean(false); public void close() throws IOException { try { super.close(); } finally { if (closed.compareAndSet(false, true)) { // important to release native memory deflater.end(); } } } }; }
38. DeflateCompressor#streamOutput()
Project: elassandra
File: DeflateCompressor.java
File: DeflateCompressor.java
@Override public StreamOutput streamOutput(StreamOutput out) throws IOException { out.writeBytes(HEADER); final boolean nowrap = true; final Deflater deflater = new Deflater(LEVEL, nowrap); final boolean syncFlush = true; OutputStream compressedOut = new DeflaterOutputStream(out, deflater, BUFFER_SIZE, syncFlush); compressedOut = new BufferedOutputStream(compressedOut, BUFFER_SIZE); return new OutputStreamStreamOutput(compressedOut) { private boolean closed = false; public void close() throws IOException { try { super.close(); } finally { if (closed == false) { // important to release native memory deflater.end(); closed = true; } } } }; }
39. HttpUtil#download()
Project: eclipse-integration-gradle
File: HttpUtil.java
File: HttpUtil.java
/** * Downloads data from a given uri and writes it to the output stream. The output stream * is closed at the end of this operation (even if the operation was not succesfull). */ public static void download(URI uri, OutputStream _out) throws IOException { BufferedOutputStream out = new BufferedOutputStream(_out); try { InputStream in = uri.toURL().openStream(); //A 4k buffer to read in data seems reasonable. byte[] buffer = new byte[1024 * 4]; int bytesRead; while ((bytesRead = in.read(buffer)) >= 0) { //0 is probably not a legitimate value for bytesRead... but just to be on the safe side :-) if (bytesRead > 0) { out.write(buffer, 0, bytesRead); } } } finally { out.close(); } }
40. IoUtils#writeBytes()
Project: drools
File: IoUtils.java
File: IoUtils.java
public static void writeBytes(File f, byte[] data) throws IOException { byte[] buf = new byte[1024]; BufferedOutputStream bos = null; ByteArrayInputStream bais = null; try { bos = new BufferedOutputStream(new FileOutputStream(f)); bais = new ByteArrayInputStream(data); int len; while ((len = bais.read(buf)) > 0) { bos.write(buf, 0, len); } } finally { if (bos != null) { bos.close(); } if (bais != null) { bais.close(); } } }
41. BitmapDiskCache#put()
Project: droidparts
File: BitmapDiskCache.java
File: BitmapDiskCache.java
public boolean put(String key, byte[] bmArr) { File file = getCachedFile(key); BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE); bos.write(bmArr); return true; } catch (Exception e) { L.w(e); return false; } finally { silentlyClose(bos); } }
42. HttpResponseCacheTest#mockIOObjects()
Project: droid-fu
File: HttpResponseCacheTest.java
File: HttpResponseCacheTest.java
private void mockIOObjects() throws Exception { whenNew(File.class).withArguments(Matchers.anyString()).thenReturn(fileMock); when(fileMock.exists()).thenReturn(true); when(fileMock.createNewFile()).thenReturn(true); when(fileMock.length()).thenReturn(11111L); mockStatic(FileInputStream.class); FileInputStream fis = mock(FileInputStream.class); whenNew(FileInputStream.class).withArguments(File.class).thenReturn(fis); mockStatic(BufferedInputStream.class); BufferedInputStream bis = mock(BufferedInputStream.class); whenNew(BufferedInputStream.class).withArguments(FileInputStream.class).thenReturn(bis); mockStatic(FileOutputStream.class); FileOutputStream fos = mock(FileOutputStream.class); whenNew(FileOutputStream.class).withArguments(File.class).thenReturn(fos); mockStatic(BufferedOutputStream.class); BufferedOutputStream bos = mock(BufferedOutputStream.class); whenNew(BufferedOutputStream.class).withArguments(FileOutputStream.class).thenReturn(bos); }
43. UIFileCopying#copy()
Project: document-viewer
File: UIFileCopying.java
File: UIFileCopying.java
public void copy(final File source, final File target) throws IOException { this.contentLength = source.length(); this.copied = 0; this.indicated = 0; this.bufsize = MathUtils.adjust((int) contentLength, 1024, 512 * 1024); final BufferedInputStream ins = new BufferedInputStream(new FileInputStream(source), bufsize); final BufferedOutputStream outs = new BufferedOutputStream(new FileOutputStream(target), bufsize); FileUtils.copy(ins, outs, bufsize, this); final String fileSize = FileUtils.getFileSize(contentLength); delegate.setProgressDialogMessage(stringId, fileSize, fileSize); }
44. Connection#connect()
Project: cordova-android-chromeview
File: Connection.java
File: Connection.java
public void connect(int connectTimeout, int readTimeout, TunnelRequest tunnelRequest) throws IOException { if (connected) { throw new IllegalStateException("already connected"); } connected = true; socket = (route.proxy.type() != Proxy.Type.HTTP) ? new Socket(route.proxy) : new Socket(); socket.connect(route.inetSocketAddress, connectTimeout); socket.setSoTimeout(readTimeout); in = socket.getInputStream(); out = socket.getOutputStream(); if (route.address.sslSocketFactory != null) { upgradeToTls(tunnelRequest); } // Use MTU-sized buffers to send fewer packets. int mtu = Platform.get().getMtu(socket); in = new BufferedInputStream(in, mtu); out = new BufferedOutputStream(out, mtu); }
45. FileUtils#writeFileUTF16()
Project: cgeo
File: FileUtils.java
File: FileUtils.java
public static boolean writeFileUTF16(final File file, final String content) { // TODO: replace by some apache.commons IOUtils or FileUtils code Writer fileWriter = null; BufferedOutputStream buffer = null; try { final OutputStream os = new FileOutputStream(file); buffer = new BufferedOutputStream(os); fileWriter = new OutputStreamWriter(buffer, CharEncoding.UTF_16); fileWriter.write(content); } catch (final IOException e) { Log.e("FieldnoteExport.ExportTask export", e); return false; } finally { IOUtils.closeQuietly(fileWriter); IOUtils.closeQuietly(buffer); } return true; }
46. ImagesList#saveToTemporaryJPGFile()
Project: cgeo
File: ImagesList.java
File: ImagesList.java
private static File saveToTemporaryJPGFile(final BitmapDrawable image) throws FileNotFoundException { final File file = LocalStorage.getStorageFile(HtmlImage.SHARED, "temp.jpg", false, true); BufferedOutputStream stream = null; try { stream = new BufferedOutputStream(new FileOutputStream(file)); image.getBitmap().compress(CompressFormat.JPEG, 100, stream); } finally { IOUtils.closeQuietly(stream); } file.deleteOnExit(); return file; }
47. 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); } }
48. 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); } }
49. FileUtil#writeStringToFile()
Project: camunda-bpm-platform
File: FileUtil.java
File: FileUtil.java
public static void writeStringToFile(String value, String filePath, boolean deleteFile) { BufferedOutputStream outputStream = null; try { File file = new File(filePath); if (file.exists() && deleteFile) { file.delete(); } outputStream = new BufferedOutputStream(new FileOutputStream(file, true)); outputStream.write(value.getBytes()); outputStream.flush(); } catch (Exception e) { throw new PerfTestException("Could not write report to file", e); } finally { IoUtil.closeSilently(outputStream); } }
50. IoUtil#writeStringToFile()
Project: camunda-bpm-platform
File: IoUtil.java
File: IoUtil.java
public static void writeStringToFile(String content, String filePath) { BufferedOutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(getFile(filePath))); outputStream.write(content.getBytes()); outputStream.flush(); } catch (Exception e) { throw LOG.exceptionWhileWritingToFile(filePath, e); } finally { IoUtil.closeSilently(outputStream); } }
51. OverwritingZipOutputStream#actuallyPutNextEntry()
Project: buck
File: OverwritingZipOutputStream.java
File: OverwritingZipOutputStream.java
@Override protected void actuallyPutNextEntry(ZipEntry entry) throws IOException { // We calculate the actual offset when closing the stream, so 0 is fine. currentEntry = new EntryAccounting(clock, entry, /* currentOffset */ 0); long md5 = Hashing.md5().hashUnencodedChars(entry.getName()).asLong(); String name = String.valueOf(md5); File file = new File(scratchDir, name); entries.put(file, currentEntry); if (file.exists() && !file.delete()) { throw new ZipException("Unable to delete existing file: " + entry.getName()); } currentOutput = new BufferedOutputStream(new FileOutputStream(file)); }
52. DefaultDefectReporter#writeReport()
Project: buck
File: DefaultDefectReporter.java
File: DefaultDefectReporter.java
private void writeReport(DefectReport defectReport, OutputStream outputStream) throws IOException { try (BufferedOutputStream baseOut = new BufferedOutputStream(outputStream); CustomZipOutputStream out = ZipOutputStreams.newOutputStream(baseOut, OVERWRITE_EXISTING)) { if (defectReport.getSourceControlInfo().isPresent() && defectReport.getSourceControlInfo().get().getDiff().isPresent()) { addStringsAsFilesToArchive(out, ImmutableMap.of(DIFF_FILE_NAME, defectReport.getSourceControlInfo().get().getDiff().get())); } addFilesToArchive(out, defectReport.getIncludedPaths()); out.putNextEntry(new CustomZipEntry(REPORT_FILE_NAME)); objectMapper.writeValue(out, defectReport); } }
53. PageRank#writeEdgesToDisk()
Project: bigtop
File: PageRank.java
File: PageRank.java
private void writeEdgesToDisk() throws IOException { this.edgesFile = File.createTempFile("fastgraph", null); FileOutputStream outStream = new FileOutputStream(this.edgesFile); BufferedOutputStream bufferedStream = new BufferedOutputStream(outStream); this.edgeDataOutputStream = new DataOutputStream(bufferedStream); for (int edgeData : edges) { this.edgeDataOutputStream.writeInt(edgeData); } this.edges.clear(); usingEdgeDiskCache = true; }
54. DependencyModule#emitDependencyInformation()
Project: bazel
File: DependencyModule.java
File: DependencyModule.java
/** * Writes dependency information to the deps file in proto format, if specified. * * This is a replacement for {@link #emitUsedClasspath} above, which only outputs the used * classpath. We collect more precise dependency information to allow Blaze to analyze both * strict and unused dependencies based on the new deps.proto. */ public void emitDependencyInformation(String classpath, boolean successful) throws IOException { if (outputDepsProtoFile == null) { return; } try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputDepsProtoFile))) { buildDependenciesProto(classpath, successful).writeTo(out); } catch (IOException ex) { throw new IOException("Cannot write dependencies to " + outputDepsProtoFile, ex); } }
55. RandomTempFile#createFile()
Project: aws-sdk-java
File: RandomTempFile.java
File: RandomTempFile.java
public void createFile(long sizeInBytes) throws IOException { deleteOnExit(); FileOutputStream outputStream = new FileOutputStream(this); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); InputStream inputStream = new RandomInputStream(sizeInBytes, binaryData); try { byte[] buffer = new byte[1024]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) > -1) { bufferedOutputStream.write(buffer, 0, bytesRead); } } finally { bufferedOutputStream.close(); outputStream.close(); inputStream.close(); } }
56. CachedOutputStream#createFileOutputStream()
Project: aries
File: CachedOutputStream.java
File: CachedOutputStream.java
private void createFileOutputStream() throws IOException { ByteArrayOutputStream bout = (ByteArrayOutputStream) currentStream; if (outputDir == null) { tempFile = File.createTempFile("cos", "tmp"); } else { tempFile = File.createTempFile("cos", "tmp", outputDir); } currentStream = new BufferedOutputStream(new FileOutputStream(tempFile)); bout.writeTo(currentStream); inmem = false; }
57. BasicSubsystem#saveDeploymentManifest()
Project: aries
File: BasicSubsystem.java
File: BasicSubsystem.java
synchronized void saveDeploymentManifest() throws IOException { File file = new File(getDirectory(), "OSGI-INF"); if (!file.exists()) file.mkdirs(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file, "DEPLOYMENT.MF"))); try { if (logger.isDebugEnabled()) logger.debug("Writing deployment manifest for subsystem {} in state {}", getSymbolicName(), getState()); deploymentManifest.write(out); if (logger.isDebugEnabled()) logger.debug("Wrote deployment manifest for subsystem {} in state {}", getSymbolicName(), getState()); } finally { IOUtils.close(out); } }
58. CachedOutputStream#createFileOutputStream()
Project: apache-aries
File: CachedOutputStream.java
File: CachedOutputStream.java
private void createFileOutputStream() throws IOException { ByteArrayOutputStream bout = (ByteArrayOutputStream) currentStream; if (outputDir == null) { tempFile = File.createTempFile("cos", "tmp"); } else { tempFile = File.createTempFile("cos", "tmp", outputDir); } currentStream = new BufferedOutputStream(new FileOutputStream(tempFile)); bout.writeTo(currentStream); inmem = false; }
59. BasicSubsystem#saveDeploymentManifest()
Project: apache-aries
File: BasicSubsystem.java
File: BasicSubsystem.java
synchronized void saveDeploymentManifest() throws IOException { File file = new File(getDirectory(), "OSGI-INF"); if (!file.exists()) file.mkdirs(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file, "DEPLOYMENT.MF"))); try { if (logger.isDebugEnabled()) logger.debug("Writing deployment manifest for subsystem {} in state {}", getSymbolicName(), getState()); deploymentManifest.write(out); if (logger.isDebugEnabled()) logger.debug("Wrote deployment manifest for subsystem {} in state {}", getSymbolicName(), getState()); } finally { IOUtils.close(out); } }
60. system#writeBytesToFile()
Project: AndroidQuickUtils
File: system.java
File: system.java
/** * Writes the specified byte[] to the specified File path. * * @param theFile File Object representing the path to write to. * @param bytes The byte[] of data to write to the File. * @throws java.io.IOException Thrown if there is problem creating or writing the * File. */ public static void writeBytesToFile(File theFile, byte[] bytes) throws IOException { BufferedOutputStream bos = null; try { FileOutputStream fos = new FileOutputStream(theFile); bos = new BufferedOutputStream(fos); bos.write(bytes); } finally { if (bos != null) { try { //flush and close the BufferedOutputStream bos.flush(); bos.close(); } catch (Exception e) { } } } }
61. 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(); } }
62. 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; }
63. EncodeJournal#exportJournal()
Project: activemq-artemis
File: EncodeJournal.java
File: EncodeJournal.java
public static void exportJournal(final String directory, final String journalPrefix, final String journalSuffix, final int minFiles, final int fileSize, final String fileName) throws Exception { try (FileOutputStream fileOutputStream = new FileOutputStream(fileName); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); PrintStream out = new PrintStream(bufferedOutputStream)) { exportJournal(directory, journalPrefix, journalSuffix, minFiles, fileSize, out); } }
64. 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); } } }
65. 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); }
66. 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(); } } }
67. Util#saveReceivedFrame()
Project: VideoRecorder
File: Util.java
File: Util.java
public static void saveReceivedFrame(SavedFrames frame) { File cachePath = new File(frame.getCachePath()); BufferedOutputStream bos; try { bos = new BufferedOutputStream(new FileOutputStream(cachePath)); if (bos != null) { bos.write(frame.getFrameBytesData()); bos.flush(); bos.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); cachePath = null; } catch (IOException e) { e.printStackTrace(); cachePath = null; } }
68. StatusTest#testSimple()
Project: urlrewritefilter
File: StatusTest.java
File: StatusTest.java
public void testSimple() throws IOException { MockRequest hsRequest = new MockRequest(); InputStream is = ConfTest.class.getResourceAsStream(ConfTest.BASE_XML_PATH + "conf-test1.xml"); Conf conf = new Conf(new MockServletContext(), is, "conf-test1.xml", "conf-test1.xml"); assertTrue(conf.getErrors().toString(), conf.isOk()); UrlRewriter urlRewriter = new UrlRewriter(conf); UrlRewriteFilter urlRewriteFilter = new UrlRewriteFilter(); Status status = new Status(urlRewriter.getConf(), urlRewriteFilter); status.displayStatusInContainer(hsRequest); assertNotNull(status.getBuffer()); assertFalse(status.getBuffer().length() == 0); // save it so we can view it File buildDir = new File("build"); if (!buildDir.exists()) buildDir.mkdir(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(buildDir, "status.html"))); try { bos.write(status.getBuffer().toString().getBytes()); } finally { bos.close(); } }
69. 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); }
70. DOMSerializeUtils#serializeToFile()
Project: team-explorer-everywhere
File: DOMSerializeUtils.java
File: DOMSerializeUtils.java
/** * <p> * Serializes the specified {@link Node} to the specified {@link File}. * </p> * * <p> * Pass the {@link #XML_DECLARATION} flag to produce an XML declaration in * the output (normally, an XML declaration is not produced). Pass the * {@link #INDENT} flag to pretty-print the output (normally, * pretty-printing is not done). To produce a doctype in the output, * <code>node</code> must be a {@link Document} and the {@link #DOCTYPE} * flag must be passed (normally, a doctype is not produced). * </p> * * <p> * Pass the {@link #BYTE_ORDER_MARK} flag to write a byte order mark to the * file for supported encodings (normally, a byte order mark is not * explicitly written; passing this flag is not recommended). * </p> * * @throws XMLException * if the serialization fails * * @param transformer * the {@link Transformer} to serialize with, or <code>null</code> to * use a {@link Transformer} from the internal pool * @param node * the {@link Node} to serialize (must not be <code>null</code>) * @param file * the {@link File} to serialize to (must not be <code>null</code>) * @param encoding * the encoding to use when writing to the {@link File}, or * <code>null</code> to not specify an encoding (passing * <code>null</code> is not recommended; passing * {@link #ENCODING_UTF8} is recommended) * @param flags * a flag value as described above, or {@link #NONE} for default * processing */ public static void serializeToFile(final Transformer transformer, final Node node, final File file, final String encoding, final int flags) { //$NON-NLS-1$ Check.notNull(file, "file"); OutputStream outputStream; try { outputStream = new FileOutputStream(file); } catch (final FileNotFoundException e) { throw new XMLException(e); } outputStream = new BufferedOutputStream(outputStream); serializeToStream(transformer, node, outputStream, encoding, flags); }
71. TestMocks#createPrintStream()
Project: tapestry4
File: TestMocks.java
File: TestMocks.java
protected PrintStream createPrintStream(File directory, String extension) throws Exception { String name = getName() + "." + extension; File file = new File(directory, name); // Open and truncate file. FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); return new PrintStream(bos, true); }
72. TestMocks#createPrintStream()
Project: tapestry3
File: TestMocks.java
File: TestMocks.java
protected PrintStream createPrintStream(File directory, String extension) throws Exception { String name = getName() + "." + extension; File file = new File(directory, name); // Open and truncate file. FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); return new PrintStream(bos, true); }
73. BufferedGZipOutputStream#openResponseOutputStream()
Project: tapestry-5
File: BufferedGZipOutputStream.java
File: BufferedGZipOutputStream.java
private void openResponseOutputStream(boolean gzip) throws IOException { OutputStream responseOutputStream = response.getOutputStream(); boolean useCompression = gzip && analyzer.isCompressable(contentType); OutputStream possiblyCompressed = useCompression ? new GZIPOutputStream(responseOutputStream) : responseOutputStream; if (useCompression) { response.setHeader(InternalConstants.CONTENT_ENCODING_HEADER, InternalConstants.GZIP_CONTENT_ENCODING); } currentOutputStream = new BufferedOutputStream(possiblyCompressed); // Write what content we already have to the new stream. byteArrayOutputStream.writeTo(currentOutputStream); byteArrayOutputStream = null; }
74. BkBasic#accept()
Project: takes
File: BkBasic.java
File: BkBasic.java
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") @Override public void accept(final Socket socket) throws IOException { try (final InputStream input = socket.getInputStream(); final BufferedOutputStream output = new BufferedOutputStream(socket.getOutputStream())) { while (true) { this.print(BkBasic.addSocketHeaders(new RqLive(input), socket), output); if (input.available() <= 0) { break; } } } }
75. UncompressUtils#uncompressTarArchiveEntry()
Project: Symfony-2-Eclipse-Plugin
File: UncompressUtils.java
File: UncompressUtils.java
/** * Uncompress a tar archive entry to the specified output directory. * * @param tarInputStream The tar input stream associated with the entry * @param entry The tar archive entry to uncompress * @param outputDirectory The output directory where to put the uncompressed entry * * @throws IOException If an error occurs within the input or output stream */ public static void uncompressTarArchiveEntry(TarArchiveInputStream tarInputStream, TarArchiveEntry entry, File outputDirectory, EntryNameTranslator entryNameTranslator) throws IOException { String entryName = entryNameTranslator.translate(entry.getName()); if (entry.isDirectory()) { createDirectory(new File(outputDirectory, entryName)); return; } File outputFile = new File(outputDirectory, entryName); ensureDirectoryHierarchyExists(outputFile); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(tarInputStream, outputStream); addExecutableBit(outputFile, Permissions.fromMode(entry.getMode())); } finally { outputStream.close(); } }
76. FileCopy#call()
Project: SKMCLauncher
File: FileCopy.java
File: FileCopy.java
@Override public File call() throws Exception { InputStream is = resource.getInputStream(); FileOutputStream fos = null; BufferedOutputStream bos = null; destination.getParentFile().mkdirs(); try { fos = new FileOutputStream(destination); bos = new BufferedOutputStream(fos); IOUtils.copy(is, bos); } finally { closeQuietly(is); closeQuietly(bos); closeQuietly(fos); } resource.cleanup(); return destination; }
77. ClsSet#save()
Project: show-java
File: ClsSet.java
File: ClsSet.java
void save(File output) throws IOException { FileUtils.makeDirsForFile(output); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(output)); try { String outputName = output.getName(); if (outputName.endsWith(CLST_EXTENSION)) { save(outputStream); } else if (outputName.endsWith(".jar")) { ZipOutputStream out = new ZipOutputStream(outputStream); try { out.putNextEntry(new ZipEntry(CLST_PKG_PATH + "/" + CLST_FILENAME)); save(out); } finally { out.close(); } } else { throw new JadxRuntimeException("Unknown file format: " + outputName); } } finally { outputStream.close(); } }
78. ByteSourceTest#createTempFile()
Project: sanselan
File: ByteSourceTest.java
File: ByteSourceTest.java
protected File createTempFile(byte src[]) throws IOException { File file = createTempFile("raw_", ".bin"); // write test bytes to file. OutputStream os = new FileOutputStream(file); os = new BufferedOutputStream(os); os.write(src); os.close(); // test that all bytes written to file. assertTrue(src.length == file.length()); return file; }
79. Utilities#copyInputToOutput()
Project: rome
File: Utilities.java
File: Utilities.java
/** * Copy input stream to output stream using 8K buffer. */ public static void copyInputToOutput(final InputStream input, final OutputStream output) throws IOException { final BufferedInputStream in = new BufferedInputStream(input); final BufferedOutputStream out = new BufferedOutputStream(output); final byte buffer[] = new byte[8192]; for (int count = 0; count != -1; ) { count = in.read(buffer, 0, 8192); if (count != -1) { out.write(buffer, 0, count); } } try { in.close(); out.close(); } catch (final IOException ex) { throw new IOException("Closing file streams, " + ex.getMessage()); } }
80. InFileBitmapObjectPersister#saveDataToCacheAndReturnData()
Project: robospice
File: InFileBitmapObjectPersister.java
File: InFileBitmapObjectPersister.java
@Override public Bitmap saveDataToCacheAndReturnData(Bitmap data, Object cacheKey) throws CacheSavingException { BufferedOutputStream out = null; try { File cacheFile = getCacheFile(cacheKey); out = new BufferedOutputStream(new FileOutputStream(cacheFile)); boolean didCompress = data.compress(compressFormat, quality, out); if (!didCompress) { throw new CacheSavingException(String.format("Could not compress bitmap for path: %s", getCacheFile(cacheKey).getAbsolutePath())); } return data; } catch (IOException e) { throw new CacheSavingException(e); } finally { IOUtils.closeQuietly(out); } }
81. SnappyCompression#decompress()
Project: Priam
File: SnappyCompression.java
File: SnappyCompression.java
private void decompress(InputStream input, OutputStream output) throws IOException { SnappyInputStream is = new SnappyInputStream(new BufferedInputStream(input)); byte data[] = new byte[BUFFER]; BufferedOutputStream dest1 = new BufferedOutputStream(output, BUFFER); try { int c; while ((c = is.read(data, 0, BUFFER)) != -1) { dest1.write(data, 0, c); } } finally { IOUtils.closeQuietly(dest1); IOUtils.closeQuietly(is); } }
82. AbstractRestore#download()
Project: Priam
File: AbstractRestore.java
File: AbstractRestore.java
/* * An overloaded download where it will not only download the object but also decrypt and uncompress. * * @param path - path of object to download from source. * @param restoreLocation - file handle to the FINAL file on disk * @param temp - file handlle to the downloaded file (i.e. file not decrypted yet). To ensure widest compatability with various encryption/decryption * algorithm, we download the file completely to disk and then decrypt. This is a temporary file and will be deleted once this behavior completes. * @param fileCrypotography - the implemented cryptography algorithm use to decrypt. * @param passPhrase - if necessary, the pass phrase use by the cryptography algorithm to decrypt. */ public void download(final AbstractBackupPath path, final File restoreLocation, final File tempFile, final IFileCryptography fileCryptography, final char[] passPhrase, final ICompression compress) throws Exception { FileOutputStream fileOs = null; BufferedOutputStream os = null; try { fileOs = new FileOutputStream(restoreLocation); os = new BufferedOutputStream(fileOs); download(path, os, tempFile, fileCryptography, passPhrase, compress); } catch (Exception e) { fileOs.close(); throw new Exception("Exception in download of: " + path.getFileName() + ", msg: " + e.getLocalizedMessage(), e); } finally { //Note: no need to close buffered outpust stream as it is done within the called download() behavior } }
83. PGStream#changeSocket()
Project: pgjdbc
File: PGStream.java
File: PGStream.java
/** * Switch this stream to using a new socket. Any existing socket is <em>not</em> closed; it's * assumed that we are changing to a new socket that delegates to the original socket (e.g. SSL). * * @param socket the new socket to change to * @throws IOException if something goes wrong */ public void changeSocket(Socket socket) throws IOException { this.connection = socket; // Submitted by Jason Venner <[email protected]>. Disable Nagle // as we are selective about flushing output only when we // really need to. connection.setTcpNoDelay(true); // Buffer sizes submitted by Sverre H Huseby <[email protected]> pg_input = new VisibleBufferedInputStream(connection.getInputStream(), 8192); pg_output = new BufferedOutputStream(connection.getOutputStream(), 8192); if (encoding != null) { setEncoding(encoding); } }
84. ParseFileUtilsTest#testReadFileToJSONObject()
Project: Parse-SDK-Android
File: ParseFileUtilsTest.java
File: ParseFileUtilsTest.java
@Test public void testReadFileToJSONObject() throws Exception { File file = temporaryFolder.newFile("file.txt"); BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); out.write(TEST_JSON.getBytes("UTF-8")); } finally { ParseIOUtils.closeQuietly(out); } JSONObject json = ParseFileUtils.readFileToJSONObject(file); assertNotNull(json); assertEquals("bar", json.getString("foo")); }
85. ParseFileUtilsTest#testReadFileToString()
Project: Parse-SDK-Android
File: ParseFileUtilsTest.java
File: ParseFileUtilsTest.java
@Test public void testReadFileToString() throws Exception { File file = temporaryFolder.newFile("file.txt"); BufferedOutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); out.write(TEST_STRING.getBytes("UTF-8")); } finally { ParseIOUtils.closeQuietly(out); } assertEquals(TEST_STRING, ParseFileUtils.readFileToString(file, "UTF-8")); }
86. Request#writeDirect()
Project: OWASP-WebScarab
File: Request.java
File: Request.java
/** Writes the Request to the supplied OutputStream, in a format appropriate for * sending to the HTTP server itself. Uses the supplied string to separate lines. * @param os the OutputStream to write to * @param crlf the string to use to separate the lines (usually a CRLF pair) * @throws IOException if the underlying stream throws any. */ public void writeDirect(OutputStream os, String crlf) throws IOException { if (_method == null || _url == null || _version == null) { System.err.println("Uninitialised Request!"); return; } os = new BufferedOutputStream(os); String requestLine = _method + " " + _url.direct() + " " + _version; os.write((requestLine + crlf).getBytes()); _logger.finer("Request: " + requestLine); super.write(os, crlf); os.flush(); }
87. Request#write()
Project: OWASP-WebScarab
File: Request.java
File: Request.java
/** * Writes the Request to the supplied OutputStream, in a format appropriate for * sending to an HTTP proxy. Uses the supplied string to separate lines. * @param os the OutputStream to write to * @param crlf the string to use to separate the lines (usually a CRLF pair) * @throws IOException if the underlying stream throws any. */ public void write(OutputStream os, String crlf) throws IOException { if (_method == null || _url == null || _version == null) { System.err.println("Uninitialised Request!"); return; } os = new BufferedOutputStream(os); String requestLine = _method + " " + _url + " " + _version + crlf; os.write(requestLine.getBytes()); _logger.finer("Request: " + requestLine); super.write(os, crlf); os.flush(); }
88. OZIPCompressionUtil#extractFile()
Project: orientdb
File: OZIPCompressionUtil.java
File: OZIPCompressionUtil.java
private static void extractFile(final ZipInputStream in, final File outdir, final String name, final OCommandOutputListener iListener) throws IOException { if (iListener != null) iListener.onMessage("\n- Uncompressing file " + name + "..."); final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir, name))); try { OIOUtils.copyStream(in, out, -1); } finally { out.close(); } }
89. WARCHeader#writeHeaderRecord()
Project: openwayback
File: WARCHeader.java
File: WARCHeader.java
private void writeHeaderRecord(File target, File fieldsSrc, String id) throws IOException { WARCWriter writer = null; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target)); FileInputStream is = new FileInputStream(fieldsSrc); ANVLRecord ar = ANVLRecord.load(is); List<String> metadata = new ArrayList<String>(1); metadata.add(ar.toString()); writer = new WARCWriter(new AtomicInteger(), bos, target, getSettings(true, null, null, metadata)); // Write a warcinfo record with description about how this WARC // was made. writer.writeWarcinfoRecord(target.getName(), "Made from " + id + " by " + this.getClass().getName()); }
90. DownloadItem#writeToFile()
Project: opensearchserver
File: DownloadItem.java
File: DownloadItem.java
public void writeToFile(File file) throws IOException { if (contentInputStream == null) return; FileOutputStream fos = null; BufferedOutputStream bos = null; try { fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); IOUtils.copy(contentInputStream, bos); } finally { IOUtils.close(bos, fos); } }
91. Utils#cat()
Project: openjdk
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); } }
92. NestedActions#writeFile()
Project: openjdk
File: NestedActions.java
File: NestedActions.java
static void writeFile(String filename) { System.out.println("WriteToFileAction: try to write to " + filename); AccessControlContext acc = AccessController.getContext(); Subject subject = Subject.getSubject(acc); System.out.println("principals = " + subject.getPrincipals()); try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filename))) { bos.write(0); bos.flush(); } catch (IOException e) { throw new RuntimeException("Unexpected IOException", e); } }
93. StAXInputFactory#getXMLStreamReader()
Project: openjdk
File: StAXInputFactory.java
File: StAXInputFactory.java
/** * @param inputstream * @throws XMLStreamException * @return */ XMLStreamReader getXMLStreamReader(Reader xmlfile) throws XMLStreamException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); BufferedOutputStream bufferedStream = new BufferedOutputStream(byteStream); StAXDocumentParser sr = null; try { XML_SAX_FI convertor = new XML_SAX_FI(); convertor.convert(xmlfile, bufferedStream); ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteStream.toByteArray()); InputStream document = new BufferedInputStream(byteInputStream); sr = new StAXDocumentParser(); sr.setInputStream(document); sr.setManager(_manager); return sr; //return new StAXDocumentParser(document, _manager); } catch (Exception e) { return null; } }
94. CommonsCompressAction#execute()
Project: logging-log4j2
File: CommonsCompressAction.java
File: CommonsCompressAction.java
/** * Compresses a file. * * @param name the compressor name, i.e. "gz", "bzip2", "xz", "pack200", or "deflate". * @param source file to compress, may not be null. * @param destination compressed file, may not be null. * @param deleteSource if true, attempt to delete file on completion. Failure to delete does not cause an exception * to be thrown or affect return value. * * @return true if source file compressed. * @throws IOException on IO exception. */ public static boolean execute(final String name, final File source, final File destination, final boolean deleteSource) throws IOException { if (!source.exists()) { return false; } try (final FileInputStream input = new FileInputStream(source); final BufferedOutputStream output = new BufferedOutputStream(new CompressorStreamFactory().createCompressorOutputStream(name, new FileOutputStream(destination)))) { IOUtils.copy(input, output, BUF_SIZE); } catch (final CompressorException e) { throw new IOException(e); } if (deleteSource && !source.delete()) { LOGGER.warn("Unable to delete " + source.toString() + '.'); } return true; }
95. FileUtils#write()
Project: LGame
File: FileUtils.java
File: FileUtils.java
/** * ????????? * * @param file * @param input * @param append * @throws IOException */ public static void write(File file, InputStream input, boolean append) throws IOException { makedirs(file); BufferedOutputStream output = null; try { int contentLength = input.available(); output = new BufferedOutputStream(new FileOutputStream(file, append)); while (contentLength-- > 0) { output.write(input.read()); } } finally { close(input); close(output); } }
96. FileUtils#write()
Project: LGame
File: FileUtils.java
File: FileUtils.java
/** * ????????? * * @param file * @param input * @param append * @throws IOException */ public static void write(File file, InputStream input, boolean append) throws IOException { makedirs(file); BufferedOutputStream output = null; try { int contentLength = input.available(); output = new BufferedOutputStream(new FileOutputStream(file, append)); while (contentLength-- > 0) { output.write(input.read()); } } finally { close(input); close(output); } }
97. ImageUtils#getSmallImageFile()
Project: KJFrameForAndroid
File: ImageUtils.java
File: ImageUtils.java
/** * ???? * * @param filePath ????? * @param width ????? * @param height ????? * @param isAdjust ????????, true????????false?????????? * @return Bitmap */ public static File getSmallImageFile(Context cxt, String filePath, int width, int height, boolean isAdjust) { Bitmap bitmap = reduce(BitmapFactory.decodeFile(filePath), width, height, isAdjust); File file = new File(getRandomFileName(cxt.getCacheDir().getPath())); BufferedOutputStream outputStream = null; try { outputStream = new BufferedOutputStream(new FileOutputStream(file)); bitmap.compress(Bitmap.CompressFormat.JPEG, 60, outputStream); outputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } return file; }
98. ObjectUtil#writeObject()
Project: jodd
File: ObjectUtil.java
File: ObjectUtil.java
/** * Writes serializable object to a file. Existing file will be overwritten. */ public static void writeObject(File dest, Object object) throws IOException { FileOutputStream fos = null; BufferedOutputStream bos = null; ObjectOutputStream oos = null; try { fos = new FileOutputStream(dest); bos = new BufferedOutputStream(fos); oos = new ObjectOutputStream(bos); oos.writeObject(object); } finally { StreamUtil.close(oos); StreamUtil.close(bos); StreamUtil.close(fos); } }
99. JimfsOutputStreamTest#testClosedOutputStream_doesNotThrowOnFlush()
Project: jimfs
File: JimfsOutputStreamTest.java
File: JimfsOutputStreamTest.java
@Test public void testClosedOutputStream_doesNotThrowOnFlush() throws IOException { JimfsOutputStream out = newOutputStream(false); out.close(); // does nothing out.flush(); try (JimfsOutputStream out2 = newOutputStream(false); BufferedOutputStream bout = new BufferedOutputStream(out2); OutputStreamWriter writer = new OutputStreamWriter(bout, UTF_8)) { /* * This specific scenario is why flush() shouldn't throw when the stream is already closed. * Nesting try-with-resources like this will cause close() to be called on the * BufferedOutputStream multiple times. Each time, BufferedOutputStream will first call * out2.flush(), then call out2.close(). If out2.flush() throws when the stream is already * closed, the second flush() will throw an exception. Prior to JDK8, this exception would be * swallowed and ignored completely; in JDK8, the exception is thrown from close(). */ } }
100. ClsSet#save()
Project: jadx
File: ClsSet.java
File: ClsSet.java
void save(File output) throws IOException { FileUtils.makeDirsForFile(output); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(output)); try { String outputName = output.getName(); if (outputName.endsWith(CLST_EXTENSION)) { save(outputStream); } else if (outputName.endsWith(".jar")) { ZipOutputStream out = new ZipOutputStream(outputStream); try { out.putNextEntry(new ZipEntry(CLST_PKG_PATH + "/" + CLST_FILENAME)); save(out); } finally { close(out); } } else { throw new JadxRuntimeException("Unknown file format: " + outputName); } } finally { close(outputStream); } }