Java Examples for java.io.BufferedOutputStream

The following java examples will help you to understand the usage of java.io.BufferedOutputStream. These source code samples are taken from different open source projects.

Example 1
Project: aetheria-master  File: Downloader.java View source code
/**
	 * Downloads file from an URL and saves it to a path in the local machine
	 * @throws FileNotFoundException, IOException 
	 */
public static void urlToFile(URL url, File path) throws FileNotFoundException, IOException {
    java.io.BufferedInputStream in = new java.io.BufferedInputStream(url.openStream());
    java.io.FileOutputStream fos = new java.io.FileOutputStream(path);
    java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
    byte[] data = new byte[1024];
    int x = 0;
    while ((x = in.read(data, 0, 1024)) >= 0) {
        bout.write(data, 0, x);
    }
    bout.close();
    in.close();
}
Example 2
Project: IronCount-master  File: ObjectSerializerTest.java View source code
@Test
public void writeHandlerToDisk() throws Exception {
    SerializedHandler h = new SerializedHandler();
    ObjectSerializer instance = new ObjectSerializer();
    byte[] result = instance.serializeObject(h);
    java.io.BufferedOutputStream bi = new BufferedOutputStream(new FileOutputStream(new File("/tmp/abd")));
    bi.write(result);
    bi.close();
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File("/tmp/abd")));
}
Example 3
Project: ChildShareClient-master  File: Utils.java View source code
public static String saveTempFile(Bitmap bm, String filePath, String fileName) throws IOException {
    File dir = new File(filePath);
    if (!dir.exists()) {
        dir.mkdir();
    }
    File file = new File(filePath, fileName);
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
    bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
    bos.flush();
    bos.close();
    return file.getPath();
}
Example 4
Project: CPP-Programs-master  File: FileDownloader.java View source code
public static void main(String args[]) throws IOException {
    java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL("http://cl.thapar.edu/qp/CH016.pdf").openStream());
    java.io.FileOutputStream fos = new java.io.FileOutputStream("t  est.pdf");
    java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
    byte[] data = new byte[1024];
    int x = 0;
    while ((x = in.read(data, 0, 1024)) >= 0) {
        bout.write(data, 0, x);
    }
    bout.close();
    in.close();
}
Example 5
Project: Docear-master  File: Tools.java View source code
public static byte[] zip(String mindmap) {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        BufferedOutputStream bufos = null;
        bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
        bufos.write(mindmap.getBytes());
        bufos.close();
        byte[] retval = bos.toByteArray();
        bos.close();
        return retval;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 6
Project: imageflow-master  File: MacroExporter.java View source code
public static void main(String[] args) {
    // example UnitList
    GraphController controller = new GraphController();
    controller.setupExample1();
    UnitList unitList = controller.getUnitElements();
    XMLEncoder e;
    try {
        e = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Test.xml")));
        e.writeObject(new JButton("test"));
        e.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
}
Example 7
Project: panovit-master  File: TestFifo.java View source code
/**
     * @param args
     */
public static void main(String[] args) {
    PrintWriter pw;
    try {
        pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream("/home/jesusr/.config/pianobar/ctl")));
        System.out.println("sending: " + args[0]);
        pw.println(args[0] + "\n");
        pw.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}
Example 8
Project: TagRec-master  File: ResultSerializer.java View source code
public static void serializePredictions(Map<Integer, Map<Integer, Double>> predictions, String filePath) {
    OutputStream file = null;
    try {
        file = new FileOutputStream(filePath);
        OutputStream buffer = new BufferedOutputStream(file);
        ObjectOutput output = new ObjectOutputStream(buffer);
        output.writeObject(predictions);
        output.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 9
Project: android_libcore-master  File: BufferedOutputStreamTest.java View source code
/**
     * @tests java.io.BufferedOutputStream#BufferedOutputStream(java.io.OutputStream,
     *        int)
     */
@TestTargetNew(level = TestLevel.COMPLETE, notes = "IllegalArgumentException checking missed.", method = "BufferedOutputStream", args = { java.io.OutputStream.class, int.class })
public void test_ConstructorLjava_io_OutputStreamI() {
    baos = new java.io.ByteArrayOutputStream();
    try {
        os = new java.io.BufferedOutputStream(baos, -1);
        fail("Test 1: IllegalArgumentException expected.");
    } catch (IllegalArgumentException e) {
    }
    try {
        os = new java.io.BufferedOutputStream(baos, 1024);
        os.write(fileString.getBytes(), 0, 500);
    } catch (java.io.IOException e) {
        fail("Test 2: Unexpected IOException.");
    }
}
Example 10
Project: CodeComb.Mobile.Android-master  File: BitmapHelper.java View source code
public static boolean saveBitmap(File file, Bitmap bitmap) {
    if (file == null || bitmap == null)
        return false;
    try {
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        return bitmap.compress(CompressFormat.JPEG, 100, out);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }
}
Example 11
Project: jvmnotebook-master  File: AsmBuilder.java View source code
public static final void main(final String[] args) throws Exception {
    System.out.println("Asm Builder");
    final ClassWriter writer = new ClassWriter(0);
    // gets the bytecode of the Example class, and loads it dynamically
    final byte[] code = writer.toByteArray();
    final OutputStream stream = new FileOutputStream("Test.class");
    final BufferedOutputStream buf = new BufferedOutputStream(stream);
    try {
        buf.write(code, 0, code.length);
        buf.flush();
    } finally {
        buf.close();
    }
    System.out.println("Done, class written to disk.");
}
Example 12
Project: millipede-master  File: RandomFile.java View source code
public static void writeRandomFile(String fileName, double size) throws IOException {
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName));
    long currentpos = 0;
    Random r = new Random();
    while (currentpos < size) {
        byte[] rndB = new byte[Main.CHUNK_LENGTH];
        r.nextBytes(rndB);
        out.write(rndB);
        currentpos = currentpos + rndB.length;
        out.flush();
    }
    out.flush();
    out.close();
}
Example 13
Project: oddjet-master  File: Oddjet4Test.java View source code
@Test
@Ignore
public void doIt() throws Exception {
    Template t = new DiplomaSupplement("./src/test/resources/diplomaSupplement.odt");
    t.getInstancePageCount();
    byte[] bytes = t.getInstancePrint();
    File f = new File("./target/copy.pdf");
    OutputStream o = new BufferedOutputStream(new FileOutputStream(f));
    o.write(bytes);
    o.close();
}
Example 14
Project: openrocket-master  File: FileUtils.java View source code
public static void copy(InputStream is, OutputStream os) throws IOException {
    if (!(os instanceof BufferedOutputStream)) {
        os = new BufferedOutputStream(os);
    }
    if (!(is instanceof BufferedInputStream)) {
        is = new BufferedInputStream(is);
    }
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = is.read(buffer)) > 0) {
        os.write(buffer, 0, bytesRead);
    }
    os.flush();
}
Example 15
Project: RMIT-Examples-master  File: WebClient.java View source code
public static void main(String[] args) {
    try {
        Socket socket = new Socket("localhost", 8771);
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter writer = new PrintWriter(new BufferedOutputStream(socket.getOutputStream()), true);
        while (true) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Please enter URL: ");
            writer.println("GET " + scanner.nextLine());
            writer.flush();
            String line;
            while (!(line = reader.readLine()).equals("END")) System.out.println(line);
        }
    } catch (Exception e) {
    }
}
Example 16
Project: usercenter-master  File: XmlSerializer.java View source code
public byte[] serialize(Object source) {
    if (source == null) {
        String msg = "argument cannot be null.";
        throw new IllegalArgumentException(msg);
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(bos));
    encoder.writeObject(source);
    encoder.close();
    return bos.toByteArray();
}
Example 17
Project: wiki-graph-master  File: WriteRedirects.java View source code
public void write(File inFile, File outFile) {
    try {
        System.out.println("Writing from " + inFile + " to " + outFile);
        BufferedReader reader = new BufferedReader(new FileReader(inFile));
        DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
        int index = 0;
        String line;
        while ((line = reader.readLine()) != null) {
            int id = Integer.parseInt(line);
            while (index < id) {
                out.writeBoolean(false);
                index++;
            }
            out.writeBoolean(true);
            index++;
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
Example 18
Project: VUE-master  File: GetContentHelper.java View source code
public boolean test(java.io.Serializable serializableObject) {
    try {
        System.out.println("Prepare to download");
        edu.tufts.osidimpl.repository.sakai.SakaiContentObject obj = (edu.tufts.osidimpl.repository.sakai.SakaiContentObject) serializableObject;
        java.io.ByteArrayInputStream in = new java.io.ByteArrayInputStream(obj.getBytes());
        java.io.BufferedOutputStream out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(obj.getDisplayName()));
        byte block[] = new byte[4096];
        int i = 0;
        try {
            while (i != -1) {
                i = in.read(block, 0, 4096);
                out.write(block, 0, 4096);
                System.out.print(".");
                if (i == -1) {
                    out.flush();
                    System.out.println();
                }
            }
        } catch (java.io.IOException ex) {
            out.flush();
        }
        System.out.println("Done downloading");
    } catch (Throwable t) {
        return false;
    }
    return true;
}
Example 19
Project: android-sdk-sources-for-api-level-23-master  File: BufferedOutputStreamTest.java View source code
public void test_flush_Constructor_NullStream() throws IOException {
    BufferedOutputStream buffos = new java.io.BufferedOutputStream(null);
    try {
        buffos.flush();
        fail("should throw NullPointerException");
    } catch (NullPointerException e) {
    }
    try {
        buffos.close();
        fail("should throw NullPointerException");
    } catch (NullPointerException e) {
    }
    buffos = new java.io.BufferedOutputStream(null, 10);
    try {
        buffos.flush();
        fail("should throw NullPointerException");
    } catch (NullPointerException e) {
    }
    try {
        buffos.close();
        fail("should throw NullPointerException");
    } catch (NullPointerException e) {
    }
    try {
        new java.io.BufferedOutputStream(null, 0);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException e) {
    }
    try {
        new java.io.BufferedOutputStream(null, -1);
        fail("should throw IllegalArgumentException");
    } catch (IllegalArgumentException e) {
    }
}
Example 20
Project: ARTPart-master  File: OldBufferedOutputStreamTest.java View source code
public void test_ConstructorLjava_io_OutputStreamI() {
    baos = new java.io.ByteArrayOutputStream();
    try {
        os = new java.io.BufferedOutputStream(baos, -1);
        fail("Test 1: IllegalArgumentException expected.");
    } catch (IllegalArgumentException e) {
    }
    try {
        os = new java.io.BufferedOutputStream(baos, 1024);
        os.write(fileString.getBytes(), 0, 500);
    } catch (java.io.IOException e) {
        fail("Test 2: Unexpected IOException.");
    }
}
Example 21
Project: abra-master  File: NativeLibraryLoader.java View source code
public void load(String tempDir) {
    String urlPath = "/libAbra.so";
    URL url = NativeLibraryLoader.class.getResource(urlPath);
    if (url != null) {
        File file = new File(tempDir + "/libAbra.so");
        try {
            final InputStream in = url.openStream();
            final OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            int len = 0;
            byte[] buffer = new byte[8192];
            while ((len = in.read(buffer)) > -1) {
                out.write(buffer, 0, len);
            }
            out.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        System.err.println("Loading native library from: " + file.getAbsolutePath());
        System.load(file.getAbsolutePath());
    } else {
        // Search library path.
        System.err.println("Searching for native library in standard path");
        System.loadLibrary("Abra");
    }
}
Example 22
Project: Android-Lib-Pen-master  File: IOUtils.java View source code
/**
     * Saves the specified bitmap to a JPG file.
     */
public static boolean write(final String path, final Bitmap bitmap) {
    OutputStream outputStream = null;
    try {
        outputStream = new BufferedOutputStream(new FileOutputStream(path));
        bitmap.compress(CompressFormat.JPEG, Constants.THUMBNAIL_QUALITY, outputStream);
        return true;
    } catch (final FileNotFoundException e) {
        Log.e(IOUtils.class.getClass().getName(), e.getMessage(), e);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (final IOException e) {
                Log.w(IOUtils.class.getClass().getName(), e.getMessage(), e);
            }
        }
        bitmap.recycle();
    }
    return false;
}
Example 23
Project: android-libcore64-master  File: OldBufferedOutputStreamTest.java View source code
public void test_ConstructorLjava_io_OutputStreamI() {
    baos = new java.io.ByteArrayOutputStream();
    try {
        os = new java.io.BufferedOutputStream(baos, -1);
        fail("Test 1: IllegalArgumentException expected.");
    } catch (IllegalArgumentException e) {
    }
    try {
        os = new java.io.BufferedOutputStream(baos, 1024);
        os.write(fileString.getBytes(), 0, 500);
    } catch (java.io.IOException e) {
        fail("Test 2: Unexpected IOException.");
    }
}
Example 24
Project: android_platform_libcore-master  File: OldBufferedOutputStreamTest.java View source code
public void test_ConstructorLjava_io_OutputStreamI() {
    baos = new java.io.ByteArrayOutputStream();
    try {
        os = new java.io.BufferedOutputStream(baos, -1);
        fail("Test 1: IllegalArgumentException expected.");
    } catch (IllegalArgumentException e) {
    }
    try {
        os = new java.io.BufferedOutputStream(baos, 1024);
        os.write(fileString.getBytes(), 0, 500);
    } catch (java.io.IOException e) {
        fail("Test 2: Unexpected IOException.");
    }
}
Example 25
Project: apptoolkit-master  File: Decompress.java View source code
public void unzip() {
    try {
        File fSourceZip = new File(_zipFile);
        String zipPath = _zipFile.substring(0, _zipFile.length() - 4);
        //File temp = new File(zipPath);
        //temp.mkdir();
        Log.v("Decompress", zipPath + " created");
        /*
             * Extract entries while creating required sub-directories
			 */
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<?> e = zipFile.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            File destinationFilePath = new File(_location, entry.getName());
            // create directories if required.
            destinationFilePath.getParentFile().mkdirs();
            // if the entry is directory, leave it. Otherwise extract it.
            if (entry.isDirectory()) {
                continue;
            } else {
                Log.v("Decompress", "Unzipping " + entry.getName());
                /*
					 * Get the InputStream for current entry of the zip file
					 * using
					 * 
					 * InputStream getInputStream(Entry entry) method.
					 */
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                byte buffer[] = new byte[1024];
                /*
					 * read the current entry from the zip file, extract it and
					 * write the extracted file.
					 */
                FileOutputStream fos = new FileOutputStream(destinationFilePath);
                BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);
                while ((b = bis.read(buffer, 0, 1024)) != -1) {
                    bos.write(buffer, 0, b);
                }
                // flush the output stream and close it.
                bos.flush();
                bos.close();
                // close the input stream.
                bis.close();
            }
        }
    } catch (IOException ioe) {
        Log.e("Decompress", "unzip", ioe);
    }
}
Example 26
Project: CatLog-Holo-master  File: RuntimeHelper.java View source code
/**
	 * Exec the arguments, using root if necessary.
	 * @param args
	 */
public static Process exec(List<String> args) throws IOException {
    // since JellyBean, sudo is required to read other apps' logs
    if (VersionHelper.getVersionSdkIntCompat() >= VersionHelper.VERSION_JELLYBEAN && !SuperUserHelper.isFailedToObtainRoot()) {
        Process process = Runtime.getRuntime().exec("su");
        PrintStream outputStream = null;
        try {
            outputStream = new PrintStream(new BufferedOutputStream(process.getOutputStream(), 8192));
            outputStream.println(TextUtils.join(" ", args));
            outputStream.flush();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
        return process;
    }
    return Runtime.getRuntime().exec(ArrayUtil.toArray(args, String.class));
}
Example 27
Project: Catlog-master  File: RuntimeHelper.java View source code
/**
	 * Exec the arguments, using root if necessary.
	 * @param args
	 */
public static Process exec(List<String> args) throws IOException {
    // since JellyBean, sudo is required to read other apps' logs
    if (VersionHelper.getVersionSdkIntCompat() >= VersionHelper.VERSION_JELLYBEAN && !SuperUserHelper.isFailedToObtainRoot()) {
        Process process = Runtime.getRuntime().exec("su");
        PrintStream outputStream = null;
        try {
            outputStream = new PrintStream(new BufferedOutputStream(process.getOutputStream(), 8192));
            outputStream.println(TextUtils.join(" ", args));
            outputStream.flush();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
        return process;
    }
    return Runtime.getRuntime().exec(ArrayUtil.toArray(args, String.class));
}
Example 28
Project: cideplus-master  File: ExporterWriter.java View source code
public void writeFilesToDir(File dir, Map<String, byte[]> exportedFiles, IProgressMonitor monitor) throws IOException {
    Set<String> keySet = exportedFiles.keySet();
    for (String fullFileName : keySet) {
        byte[] bytesToWrite = exportedFiles.get(fullFileName);
        monitor.setTaskName("Writing... " + fullFileName);
        monitor.worked(1);
        if (bytesToWrite.length == 0) {
            continue;
        }
        File fileDir = new File(dir, getDir(fullFileName));
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File file = new File(fileDir, getFile(fullFileName));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        try {
            out.write(bytesToWrite);
            out.flush();
        } finally {
            out.close();
        }
    }
}
Example 29
Project: CIMTool-master  File: Convert.java View source code
/**
	 * Convert an RDF file from one syntax to another.
	 * @throws IOException 
	 */
public static void main(String[] args) throws IOException {
    if (args.length < 2 || args.length > 5) {
        System.err.println("arguments: input_file output_file [input_lang [output_lang [base_uri]]]");
        return;
    }
    String input = args[0];
    String output = args[1];
    String inputLang = args.length > 2 ? args[2] : "TTL";
    String outputLang = args.length > 3 ? args[3] : "RDF/XML";
    String base = args.length > 4 ? args[4] : "http://langdale.com.au/2008/network#";
    Model model = ModelFactory.createDefaultModel();
    model.read(new BufferedInputStream(new FileInputStream(input)), base, inputLang);
    model.write(new BufferedOutputStream(new FileOutputStream(output)), outputLang, base);
}
Example 30
Project: clade-master  File: ResultStoringMonitor.java View source code
public double valueAt(double[] x) {
    if (++i % outputFreq == 0) {
        System.err.print("Storing interim (double) weights to " + filename + " ... ");
        try {
            DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(filename))));
            Convert.saveDoubleArr(dos, x);
            dos.close();
        } catch (IOException e) {
            System.err.println("ERROR!");
            return 1;
        }
        System.err.println("DONE.");
    }
    return 0;
}
Example 31
Project: codeine-master  File: SerializationUtils.java View source code
public static void toFile(String file, Object o) {
    try (OutputStream f = new FileOutputStream(file);
        OutputStream buffer = new BufferedOutputStream(f);
        ObjectOutput output = new ObjectOutputStream(buffer)) {
        output.writeObject(o);
    } catch (IOException ex) {
        throw ExceptionUtils.asUnchecked(ex);
    }
}
Example 32
Project: commonj-master  File: BinaryFileWriter.java View source code
public void write(byte[] byteData, Path savePath) throws IllegalArgumentException, IOException {
    if (savePath == null) {
        throw new IllegalArgumentException("Path cannot be null");
    }
    if (byteData == null) {
        throw new IllegalArgumentException("Data cannot be null");
    }
    if (savePath != null && savePath.getParent() != null) {
        Files.createDirectories(savePath.getParent());
    }
    try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(savePath, CREATE, TRUNCATE_EXISTING))) {
        os.write(byteData);
    }
}
Example 33
Project: CoreNLP-master  File: ResultStoringMonitor.java View source code
public double valueAt(double[] x) {
    if (++i % outputFreq == 0) {
        log.info("Storing interim (double) weights to " + filename + " ... ");
        try {
            DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(filename))));
            ConvertByteArray.saveDoubleArr(dos, x);
            dos.close();
        } catch (IOException e) {
            log.error("!");
            return 1;
        }
        log.info("DONE.");
    }
    return 0;
}
Example 34
Project: deeplearning4j-master  File: BaseUiServerTest.java View source code
//    protected static UiServer uiServer;
//    protected static Client client = ClientBuilder.newClient().register(JacksonJsonProvider.class).register(new ObjectMapperProvider());
@BeforeClass
public static void before() throws Exception {
    ClassPathResource resource = new ClassPathResource("dropwizard.yml");
    InputStream is = resource.getInputStream();
    final File tmpConfig = new File("dropwizard-render.yml");
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpConfig));
    IOUtils.copy(is, bos);
    bos.flush();
    bos.close();
    is.close();
    tmpConfig.deleteOnExit();
//        uiServer = new UiServer();
//        try {
//            uiServer.run("server", tmpConfig.getAbsolutePath());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
}
Example 35
Project: docmatic-master  File: SingleFileRenderer.java View source code
public void render(Document document, Theme theme, File outputFile) throws RenderException {
    RenderableDocument renderableDocument = new RenderableDocument();
    theme.getDocumentBuilder().buildDocument(document, renderableDocument);
    LOGGER.info("Generating {}.", outputFile);
    try {
        outputFile.getParentFile().mkdirs();
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(outputFile));
        try {
            doRender(renderableDocument, theme, stream);
        } finally {
            stream.close();
        }
    } catch (Exception e) {
        throw new RenderException(String.format("Could not render document to '%s'.", outputFile), e);
    }
}
Example 36
Project: EDU_SYZT-master  File: FileUploadController.java View source code
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            stream.write(bytes);
            stream.close();
            return "You successfully uploaded " + name + "!";
        } catch (Exception e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}
Example 37
Project: Effects-Pro-master  File: BitmapWriter.java View source code
@Override
protected Boolean doInBackground(Void... arg0) {
    try {
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file, true);
        final BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE);
        bitmap.compress(CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        fos.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}
Example 38
Project: fdroidclient-master  File: BluetoothConnection.java View source code
@TargetApi(14)
public void open() throws IOException {
    if (Build.VERSION.SDK_INT >= 14 && !socket.isConnected()) {
        // Server sockets will already be connected when they are passed to us,
        // client sockets require us to call connect().
        socket.connect();
    }
    input = new BufferedInputStream(socket.getInputStream());
    output = new BufferedOutputStream(socket.getOutputStream());
    Utils.debugLog(TAG, "Opened connection to Bluetooth device");
}
Example 39
Project: geoserver-2.0.x-master  File: FlatFileStorage.java View source code
public List<String> handleUpload(String contentType, File content, UniqueIDGenerator generator, File uploadDirectory) throws IOException {
    String originalName = "";
    String name = generator.generate(originalName);
    InputStream in = new BufferedInputStream(new FileInputStream(content));
    File storedFile = new File(uploadDirectory, name);
    OutputStream out = new BufferedOutputStream(new FileOutputStream(storedFile));
    copyStream(in, out);
    in.close();
    out.flush();
    out.close();
    List<String> result = new ArrayList<String>();
    result.add(name);
    return result;
}
Example 40
Project: GPT-Organize-master  File: TGSongWriter.java View source code
public void write(TGFactory factory, TGSong song, String path) throws TGFileFormatException {
    try {
        Iterator it = TGFileFormatManager.instance().getOutputStreams();
        while (it.hasNext()) {
            TGOutputStreamBase writer = (TGOutputStreamBase) it.next();
            if (isSupportedExtension(writer, path)) {
                writer.init(factory, new BufferedOutputStream(new FileOutputStream(new File(path))));
                writer.writeSong(song);
                return;
            }
        }
    } catch (Throwable t) {
        throw new TGFileFormatException(t);
    }
    throw new TGFileFormatException("Unsupported file format");
}
Example 41
Project: grails-lightweight-deploy-master  File: Utils.java View source code
public static void unzip(ZipEntry entry, ZipFile zipfile, File explodedDir) throws IOException {
    if (entry.isDirectory()) {
        new File(explodedDir, entry.getName()).mkdirs();
        return;
    }
    File outputFile = new File(explodedDir, entry.getName());
    if (!outputFile.getParentFile().exists()) {
        outputFile.getParentFile().mkdirs();
    }
    BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
    try {
        ByteStreams.copy(inputStream, outputStream);
    } finally {
        outputStream.close();
        inputStream.close();
    }
}
Example 42
Project: GT-master  File: RuntimeHelper.java View source code
/**
	 * Exec the arguments, using root if necessary.
	 * @param args
	 */
public static Process exec(List<String> args) throws IOException {
    // since JellyBean, sudo is required to read other apps' logs
    if (VersionHelper.getVersionSdkIntCompat() >= VersionHelper.VERSION_JELLYBEAN && RootUtil.isRooted()) {
        Process process = Runtime.getRuntime().exec("su");
        PrintStream outputStream = null;
        try {
            outputStream = new PrintStream(new BufferedOutputStream(process.getOutputStream(), 8192));
            outputStream.println(TextUtils.join(" ", args));
            outputStream.flush();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
        return process;
    }
    return Runtime.getRuntime().exec(ArrayUtil.toArray(args, String.class));
}
Example 43
Project: HotFix-master  File: Utils.java View source code
public static boolean prepareDex(Context context, File dexInternalStoragePath, String dex_file) {
    BufferedInputStream bis = null;
    OutputStream dexWriter = null;
    try {
        bis = new BufferedInputStream(context.getAssets().open(dex_file));
        dexWriter = new BufferedOutputStream(new FileOutputStream(dexInternalStoragePath));
        byte[] buf = new byte[BUF_SIZE];
        int len;
        while ((len = bis.read(buf, 0, BUF_SIZE)) > 0) {
            dexWriter.write(buf, 0, len);
        }
        dexWriter.close();
        bis.close();
        return true;
    } catch (IOException e) {
        if (dexWriter != null) {
            try {
                dexWriter.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        return false;
    }
}
Example 44
Project: irma_personalisation-master  File: Logger.java View source code
public static void log(String message, Exception e) {
    PrintStream stream = null;
    try {
        stream = new PrintStream(new BufferedOutputStream(new FileOutputStream(LOG_FILENAME, true)));
        stream.append(String.format("===========================================%n" + "%tc: %s%n", new Date(), message));
        e.printStackTrace(stream);
        stream.append(String.format("%n%n"));
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
Example 45
Project: j2objc-master  File: OldBufferedOutputStreamTest.java View source code
public void test_ConstructorLjava_io_OutputStreamI() {
    baos = new java.io.ByteArrayOutputStream();
    try {
        os = new java.io.BufferedOutputStream(baos, -1);
        fail("Test 1: IllegalArgumentException expected.");
    } catch (IllegalArgumentException e) {
    }
    try {
        os = new java.io.BufferedOutputStream(baos, 1024);
        os.write(fileString.getBytes(), 0, 500);
    } catch (java.io.IOException e) {
        fail("Test 2: Unexpected IOException.");
    }
}
Example 46
Project: java-weboslib-master  File: JarResource.java View source code
public File extract(File dest) {
    try {
        if (dest.exists())
            dest.delete();
        InputStream in = null;
        if (specific == null) {
            in = new BufferedInputStream(this.getClass().getResourceAsStream(path));
        } else {
            in = new BufferedInputStream(specific.getResourceAsStream(path));
        }
        OutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
        byte[] buffer = new byte[2048];
        for (; ; ) {
            int nBytes = in.read(buffer);
            if (nBytes <= 0)
                break;
            out.write(buffer, 0, nBytes);
        }
        out.flush();
        out.close();
        in.close();
        return dest;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Example 47
Project: javablog-master  File: StreamNio.java View source code
@Test
public void testWrite() {
    //通过Files类获得输出�
    try (BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(Paths.get("src/test2.txt"), StandardOpenOption.CREATE, StandardOpenOption.WRITE))) {
        for (int i = 0; i < 26; i++) out.write((byte) ('A' + i));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 48
Project: javacuriosities-master  File: Step2ClientSocketTCP.java View source code
public static void main(String[] args) {
    try (Socket socketToConnet = new Socket(InetAddress.getLocalHost(), 9500)) {
        System.out.println("Connecting...");
        // receive file
        byte[] bytes = new byte[5];
        InputStream is = socketToConnet.getInputStream();
        FileOutputStream fos = new FileOutputStream("data_backup.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int bytesRead = 0;
        while ((bytesRead = is.read(bytes)) != -1) {
            System.out.println("Receiving file (" + bytesRead + " bytes)");
            bos.write(bytes, 0, bytesRead);
        }
        bos.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 49
Project: JPaxos-master  File: BarrierClient.java View source code
public void enterBarrier(String host, int port, int requests, long time, int number) {
    try {
        Socket skt = new Socket(host, port);
        // System.out.println("# " + requests + " " + time);
        DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(skt.getOutputStream()));
        dos.writeInt(number);
        dos.writeInt(requests);
        dos.writeLong(time);
        dos.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
        while (!in.ready()) {
        }
        in.readLine();
        in.close();
        dos.close();
        skt.close();
    } catch (Exception e) {
        System.out.print("Whoops! It didn't work!\n");
        System.exit(1);
    }
}
Example 50
Project: jsunit-master  File: XmlResult.java View source code
public void execute(ActionInvocation invocation) throws Exception {
    XmlProducer producer = (XmlProducer) invocation.getAction();
    XmlRenderable xmlRenderable = producer.getXmlRenderable();
    Element element = xmlRenderable.asXml();
    Document document = new Document(element);
    String xmlString = XmlUtility.asString(document);
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("text/xml");
    try {
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
        bufferedOut.write(xmlString.getBytes());
        bufferedOut.close();
    } catch (IOException e) {
        logger.warning("Failed to write result XML response to browser: " + e.toString());
    }
}
Example 51
Project: LunarTabsAndroid-master  File: TGSongWriter.java View source code
public void write(TGFactory factory, TGSong song, String path) throws TGFileFormatException {
    try {
        Iterator it = TGFileFormatManager.instance().getOutputStreams();
        while (it.hasNext()) {
            TGOutputStreamBase writer = (TGOutputStreamBase) it.next();
            if (isSupportedExtension(writer, path)) {
                writer.init(factory, new BufferedOutputStream(new FileOutputStream(new File(path))));
                writer.writeSong(song);
                return;
            }
        }
    } catch (Throwable t) {
        throw new TGFileFormatException(t);
    }
    throw new TGFileFormatException("Unsupported file format");
}
Example 52
Project: mapfish-print-master  File: HibernatePrintJob.java View source code
@Override
protected final URI withOpenOutputStream(final PrintAction function) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    BufferedOutputStream bout = new BufferedOutputStream(out);
    try {
        function.run(bout);
        this.data = out.toByteArray();
    } finally {
        bout.close();
    }
    return new URI("hibernate:" + getEntry().getReferenceId());
}
Example 53
Project: mathematorium-master  File: ActionScriptSaveUtilities.java View source code
/**
	 * Saves the current model of the history in the specified File.
	 * 
	 * @param outputFile
	 */
public static void saveScript(File outputFile) {
    ExpressionConsoleHistory expressionHistory = ExpressionConsoleModel.getInstance().getExpressionHistory();
    try {
        XMLEncoder e = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(outputFile)));
        e.writeObject(expressionHistory);
        e.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 54
Project: MinecraftForkage-master  File: Pack200Task.java View source code
@Override
public void execute() throws BuildException {
    if (input == null)
        throw new BuildException("input file not specified");
    if (output == null)
        throw new BuildException("output file not specified");
    try (JarFile in = new JarFile(input)) {
        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(output))) {
            Pack200.newPacker().pack(in, out);
        }
    } catch (Exception e) {
        throw new BuildException(e);
    }
}
Example 55
Project: monkeytest-master  File: XmlResult.java View source code
public void execute(ActionInvocation invocation) throws Exception {
    XmlProducer producer = (XmlProducer) invocation.getAction();
    XmlRenderable xmlRenderable = producer.getXmlRenderable();
    Element element = xmlRenderable.asXml();
    Document document = new Document(element);
    String xmlString = XmlUtility.asString(document);
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("text/xml");
    try {
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
        bufferedOut.write(xmlString.getBytes());
        bufferedOut.close();
    } catch (IOException e) {
        logger.warning("Failed to write result XML response to browser: " + e.toString());
    }
}
Example 56
Project: OG-Platform-master  File: RecordNetworkStream.java View source code
public static void main(final String[] args) throws IOException {
    // CSIGNORE
    final String host = args[0];
    final Integer port = Integer.parseInt(args[1]);
    final String file = args[2];
    try (Socket socket = new Socket(host, port)) {
        try (BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file))) {
            final BufferedInputStream input = new BufferedInputStream(socket.getInputStream());
            try {
                final byte[] buffer = new byte[4096];
                final long start = System.nanoTime();
                while (System.nanoTime() - start < 300000000000L) {
                    final int bytes = input.read(buffer);
                    if (bytes < 0) {
                        return;
                    }
                    output.write(buffer, 0, bytes);
                }
            } finally {
                input.close();
            }
        }
    }
}
Example 57
Project: omc-lib-master  File: NBTUtil.java View source code
public static void writeToFile(final CompoundTag tag, final File file, final boolean compress) throws IOException {
    DataOutputStream out;
    if (compress) {
        out = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(file))));
    } else {
        out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
    }
    NBTTag.writeTag(tag, out);
    out.flush();
    out.close();
}
Example 58
Project: Path-of-Exile-Racer-master  File: RawTypeface.java View source code
private static void copyToFile(Context context, int resId, File outFile) throws IOException {
    InputStream is = context.getResources().openRawResource(resId);
    byte[] buffer = new byte[is.available()];
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile));
    try {
        int read = 0;
        while ((read = is.read(buffer)) > 0) {
            bos.write(buffer, 0, read);
        }
    } finally {
        bos.close();
        is.close();
    }
}
Example 59
Project: phenoscape-nlp-master  File: ParsingUtil.java View source code
public static void outputXML(Element treatment, File file, Comment comment) throws ParsingException {
    try {
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        Document doc = new Document(treatment);
        // File file = new File(path, dest + "/" + count + ".xml");
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        outputter.output(doc, out);
        if (comment != null)
            outputter.output(comment, out);
        // don't forget to close the output stream!!!
        out.close();
    // generate the information to the listener (gui)
    // listener.info(String.valueOf(count), "", file.getPath());
    } catch (IOException e) {
        LOGGER.error("Exception in ParsingUtil:outputXML");
        e.printStackTrace();
        throw new ParsingException(e);
    }
}
Example 60
Project: polly-master  File: GsonHttpAnswerHandler.java View source code
@Override
public void handleAnswer(HttpAnswer answer, HttpEvent e, OutputStream out) throws IOException {
    try {
        final GsonHttpAnswer gsonAnswer = (GsonHttpAnswer) answer;
        final Gson gson = new GsonBuilder().setPrettyPrinting().create();
        // TODO: hardcoded reference to encoding
        final Writer w = new OutputStreamWriter(new BufferedOutputStream(out), //$NON-NLS-1$
        "UTF-8");
        w.write(gson.toJson(gsonAnswer.getValue()));
        w.flush();
    } catch (Exception e1) {
        e1.printStackTrace();
        throw e1;
    }
}
Example 61
Project: postal-master  File: SysInfoUtil.java View source code
public static void saveBitmapToFile(Bitmap bitmap, String _file) throws IOException {
    BufferedOutputStream os = null;
    try {
        File file = new File(_file);
        // String _filePath_file.replace(File.separatorChar +
        // file.getName(), "");
        int end = _file.lastIndexOf(File.separator);
        String _filePath = _file.substring(0, end);
        File filePath = new File(_filePath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        file.createNewFile();
        os = new BufferedOutputStream(new FileOutputStream(file));
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                System.err.println(e.toString());
            }
        }
    }
}
Example 62
Project: projecteuler-master  File: Decompress.java View source code
public static void unzip(InputStream fin, String location) {
    dirChecker(location, "");
    try {
        ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fin));
        ZipEntry ze = null;
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.isDirectory())
                dirChecker(location, ze.getName());
            else {
                File f = new File(location + ze.getName());
                f.getParentFile().mkdirs();
                BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(location + ze.getName()));
                int BUFFER_SIZE = 2048;
                byte b[] = new byte[BUFFER_SIZE];
                int n;
                while ((n = zin.read(b, 0, BUFFER_SIZE)) >= 0) fout.write(b, 0, n);
                zin.closeEntry();
                fout.close();
            }
        }
        zin.close();
    } catch (Exception e) {
        String s = e.getMessage();
        Log.e("DB Error", s);
    }
}
Example 63
Project: risky-master  File: TestingUtil.java View source code
static void writeTwoBinaryFixes(String filename, BinaryFixesFormat format) {
    try {
        OutputStream os = new BufferedOutputStream(new FileOutputStream(filename));
        long t = 1421708455237L;
        Fix fix1 = new FixImpl(213456789, -10f, 135f, t, of(12), of((short) 1), of(NavigationalStatus.ENGAGED_IN_FISHING), of(7.5f), of(45f), of(46f), AisClass.B);
        Fix fix2 = new FixImpl(213456789, -10.1f, 135.2f, t + 1000 * 3600 * 2L, of(13), of((short) 2), of(NavigationalStatus.AT_ANCHOR), of(4.5f), of(20f), of(30f), AisClass.B);
        BinaryFixes.write(fix1, os, format);
        BinaryFixes.write(fix2, os, format);
        os.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 64
Project: robovm-master  File: OldBufferedOutputStreamTest.java View source code
public void test_ConstructorLjava_io_OutputStreamI() {
    baos = new java.io.ByteArrayOutputStream();
    try {
        os = new java.io.BufferedOutputStream(baos, -1);
        fail("Test 1: IllegalArgumentException expected.");
    } catch (IllegalArgumentException e) {
    }
    try {
        os = new java.io.BufferedOutputStream(baos, 1024);
        os.write(fileString.getBytes(), 0, 500);
    } catch (java.io.IOException e) {
        fail("Test 2: Unexpected IOException.");
    }
}
Example 65
Project: roman10-android-tutorial-master  File: Test.java View source code
public static void main(String[] args) throws IOException {
    Movie movie = new MovieCreator().build(new IsoBufferWrapperImpl(new File("/home/sannies/suckerpunch-samurai_h640w.mov")));
    IsoFile out = new DefaultMp4Builder().build(movie);
    FileOutputStream fos = new FileOutputStream("/home/sannies/suckerpunch-samurai_h640w.mp4");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    out.getBox(new IsoOutputStream(bos));
    bos.close();
    IsoFile reread = new IsoFile(new IsoBufferWrapperImpl(new File("/home/sannies/suckerpunch-samurai_h640w.mp4")));
    reread.parse();
}
Example 66
Project: SEEPng-master  File: WriteToChannelWriteToBufferedOutputTest.java View source code
public static void main(String args[]) throws IOException {
    // vars
    String file = "testChannel";
    String file2 = "testBuffered";
    long size = 1024 * 1024 * 1024;
    ByteBuffer bb = ByteBuffer.allocate((int) size);
    long s = System.nanoTime();
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file2), 4 * 1024 * 1024);
    byte[] payload = bb.array();
    int limit2 = bb.limit();
    bos.write(limit2);
    bos.write(payload, 0, payload.length);
    bos.flush();
    bos.close();
    long e = System.nanoTime();
    System.out.println("bufferedoutput: " + (e - s));
    // channel
    s = System.nanoTime();
    WritableByteChannel bc = Channels.newChannel(new FileOutputStream(file, true));
    int limit = bb.limit();
    ByteBuffer limitInt = ByteBuffer.allocate(Integer.BYTES).putInt(limit);
    bc.write(limitInt);
    bc.write(bb);
    bc.close();
    e = System.nanoTime();
    System.out.println("channel: " + (e - s));
}
Example 67
Project: solrmeter-master  File: HeadlessQueryTimeHistoryPanel.java View source code
@Override
public void refreshView() {
    if (!statistic.getCurrentHistory().isEmpty()) {
        try {
            File outFile = HeadlessUtils.getOutputFile(PREFIX + "title", HeadlessConsoleFrame.getStatisticsOutputDirectory());
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile));
            statistic.printQueriesTimeToStream(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Example 68
Project: spring-guides-master  File: FileUploadController.java View source code
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)))) {
                stream.write(file.getBytes());
            }
            return "You successfully uploaded " + name + "!";
        } catch (IOException e) {
            return "You failed to upload " + name + " => " + e.getMessage();
        }
    } else {
        return "You failed to upload " + name + " because the file was empty.";
    }
}
Example 69
Project: stan-cn-com-master  File: ResultStoringMonitor.java View source code
public double valueAt(double[] x) {
    if (++i % outputFreq == 0) {
        System.err.print("Storing interim (double) weights to " + filename + " ... ");
        try {
            DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(filename))));
            ConvertByteArray.saveDoubleArr(dos, x);
            dos.close();
        } catch (IOException e) {
            System.err.println("ERROR!");
            return 1;
        }
        System.err.println("DONE.");
    }
    return 0;
}
Example 70
Project: stanford-corenlp-master  File: ResultStoringMonitor.java View source code
public double valueAt(double[] x) {
    if (++i % outputFreq == 0) {
        System.err.print("Storing interim (double) weights to " + filename + " ... ");
        try {
            DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(filename))));
            Convert.saveDoubleArr(dos, x);
            dos.close();
        } catch (IOException e) {
            System.err.println("ERROR!");
            return 1;
        }
        System.err.println("DONE.");
    }
    return 0;
}
Example 71
Project: stanford-ner-master  File: ResultStoringMonitor.java View source code
public double valueAt(double[] x) {
    if (++i % outputFreq == 0) {
        System.err.print("Storing interim (double) weights to " + filename + " ... ");
        try {
            DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(filename))));
            Convert.saveDoubleArr(dos, x);
            dos.close();
        } catch (IOException e) {
            System.err.println("ERROR!");
            return 1;
        }
        System.err.println("DONE.");
    }
    return 0;
}
Example 72
Project: Stanford-NLP-master  File: ResultStoringMonitor.java View source code
public double valueAt(double[] x) {
    if (++i % outputFreq == 0) {
        log.info("Storing interim (double) weights to " + filename + " ... ");
        try {
            DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(filename))));
            ConvertByteArray.saveDoubleArr(dos, x);
            dos.close();
        } catch (IOException e) {
            log.error("!");
            return 1;
        }
        log.info("DONE.");
    }
    return 0;
}
Example 73
Project: teavm-master  File: DirectoryBuildTarget.java View source code
@Override
public OutputStream createResource(String fileName) throws IOException {
    int index = fileName.lastIndexOf('/');
    if (index >= 0) {
        File dir = new File(directory, fileName.substring(0, index));
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }
    return new BufferedOutputStream(new FileOutputStream(new File(directory, fileName)), 65536);
}
Example 74
Project: test-driven-javascript-example-application-master  File: XmlResult.java View source code
public void execute(ActionInvocation invocation) throws Exception {
    XmlProducer producer = (XmlProducer) invocation.getAction();
    XmlRenderable xmlRenderable = producer.getXmlRenderable();
    Element element = xmlRenderable.asXml();
    Document document = new Document(element);
    String xmlString = XmlUtility.asString(document);
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("text/xml");
    try {
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
        bufferedOut.write(xmlString.getBytes());
        bufferedOut.close();
    } catch (IOException e) {
        logger.warning("Failed to write result XML response to browser: " + e.toString());
    }
}
Example 75
Project: Testing-and-Debugging-JavaScript-master  File: XmlResult.java View source code
public void execute(ActionInvocation invocation) throws Exception {
    XmlProducer producer = (XmlProducer) invocation.getAction();
    XmlRenderable xmlRenderable = producer.getXmlRenderable();
    Element element = xmlRenderable.asXml();
    Document document = new Document(element);
    String xmlString = XmlUtility.asString(document);
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("text/xml");
    try {
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
        bufferedOut.write(xmlString.getBytes());
        bufferedOut.close();
    } catch (IOException e) {
        logger.warning("Failed to write result XML response to browser: " + e.toString());
    }
}
Example 76
Project: timelapse-sony-master  File: FileRequest.java View source code
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(mOutputFile));
        bos.write(response.data);
        bos.flush();
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
}
Example 77
Project: tizzit-master  File: PictureUploadUtilTest.java View source code
@Test
public void testGetBytesFromFile() throws IOException {
    File file = File.createTempFile("JUnit_", ".garbage");
    file.createNewFile();
    byte[] bs = PictureUploadUtil.getBytesFromFile(file);
    assertEquals(0, bs.length);
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    bos.write(new byte[] { 0x11, 0x12 });
    bos.flush();
    bos.close();
    fos.flush();
    fos.close();
    bs = PictureUploadUtil.getBytesFromFile(file);
    assertEquals(2, bs.length);
    file.delete();
}
Example 78
Project: TuxGuitar-master  File: TGSongWriter.java View source code
public void write(TGSong song, String path) throws TGFileFormatException {
    try {
        for (final TGOutputStreamBase writer : TGFileFormatManager.instance().getOutputStreams()) {
            if (isSupportedExtension(writer, path)) {
                writer.init(new BufferedOutputStream(new FileOutputStream(new File(path))));
                writer.writeSong(song);
                return;
            }
        }
    } catch (Throwable t) {
        throw new TGFileFormatException(t);
    }
    throw new TGFileFormatException("Unsupported file format");
}
Example 79
Project: w3act-master  File: HttpBasicAuth.java View source code
public static void downloadFileWithAuth(String urlStr, String user, String pass, String outFilePath) {
    try {
        URL url = new URL(urlStr);
        String authStr = user + ":" + pass;
        String authEncoded = Base64.encodeBytes(authStr.getBytes());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setRequestProperty("Authorization", "Basic " + authEncoded);
        File file = new File(outFilePath);
        InputStream in = (InputStream) connection.getInputStream();
        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        for (int b; (b = in.read()) != -1; ) {
            out.write(b);
        }
        out.close();
        in.close();
    } catch (Exception e) {
        Logger.debug("downloadFileWithAuth() error: " + e);
        e.printStackTrace();
    }
}
Example 80
Project: wmf2svg-master  File: SvgGdiTest.java View source code
@Test
public void testPie() throws Exception {
    SvgGdi gdi = new SvgGdi();
    gdi.placeableHeader(0, 0, 9000, 9000, 1440);
    gdi.header();
    gdi.setWindowOrgEx(0, 0, null);
    gdi.setWindowExtEx(200, 200, null);
    gdi.setBkMode(1);
    GdiBrush brush1 = gdi.createBrushIndirect(1, 0, 0);
    gdi.selectObject(brush1);
    gdi.rectangle(10, 10, 110, 110);
    GdiPen pen2 = gdi.createPenIndirect(0, 1, 0x0000FF);
    gdi.selectObject(pen2);
    gdi.pie(10, 10, 110, 110, 60, 10, 110, 60);
    gdi.footer();
    File file = new File(System.getProperty("user.home") + "/wmf2svg", "pie_test.svg");
    file.getParentFile().mkdirs();
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    try {
        gdi.write(out);
    } finally {
        out.close();
    }
}
Example 81
Project: xmlvm.svn-master  File: JarUtil.java View source code
public static void copy(String fromJar, String toPath) {
    try {
        JarInputStream libFiles = new JarInputStream(Main.class.getResourceAsStream(fromJar));
        if (!toPath.endsWith(File.separator))
            toPath += File.separator;
        File dir = new File(toPath);
        if (!dir.exists())
            dir.mkdirs();
        JarEntry file = null;
        while ((file = libFiles.getNextJarEntry()) != null) {
            final int BUFFER = 2048;
            int count;
            byte data[] = new byte[BUFFER];
            // write the files to the disk
            FileOutputStream fos = new FileOutputStream(toPath + file.getName());
            BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = libFiles.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        System.exit(-1);
    }
}
Example 82
Project: AiyaEffectsAndroid-master  File: FileUtil.java View source code
public static void saveBitmap(Bitmap b) {
    String path = initPath();
    long dataTake = System.currentTimeMillis();
    String jpegName = path + "/" + dataTake + ".jpg";
    Log.i(TAG, "saveBitmap:jpegName = " + jpegName);
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 83
Project: AMIDST-master  File: ByteArrayHub.java View source code
public void unload() {
    try {
        BufferedOutputStream outStream = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(path)));
        outStream.write(data, 0, data.length);
        outStream.flush();
        outStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 84
Project: AndRoad-master  File: GPXToFileWriter.java View source code
@Override
public void run() {
    try {
        // Ensure folder exists
        final String traceFolderPath = Util.getAndRoadExternalStoragePath() + SDCARD_SAVEDTRACES_PATH;
        new File(traceFolderPath).mkdirs();
        // Create file and ensure that needed folders exist.
        final String filename = SDF.format(new Date(System.currentTimeMillis())) + ".gpx";
        final File dest = new File(traceFolderPath + filename + ".zip");
        // Write Data
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(dest), StreamUtils.IO_BUFFER_SIZE);
        final byte[] data = org.androad.osm.api.traces.util.Util.zipBytes(RecordedRouteGPXFormatter.create(recordedGeoPoints).getBytes(), filename);
        out.write(data);
        out.flush();
        out.close();
    } catch (final Exception e) {
        Log.e(OSMConstants.DEBUGTAG, "File-Writing-Error", e);
    }
}
Example 85
Project: AndroidExercise-master  File: ImageUtil.java View source code
public static void inputStream2File(InputStream inputStream, File file) {
    BufferedOutputStream bos = null;
    try {
        bos = new BufferedOutputStream(new FileOutputStream(file));
        byte[] b = new byte[1024];
        int len;
        while ((len = inputStream.read(b)) != -1) {
            bos.write(b, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 86
Project: annotateThrift-master  File: WriteStruct.java View source code
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println("usage: java -cp build/classes org.apache.thrift.test.WriteStruct filename proto_factory_class");
        System.out.println("Write out an instance of Fixtures.compactProtocolTestStruct to 'file'. Use a protocol from 'proto_factory_class'.");
    }
    TTransport trans = new TIOStreamTransport(new BufferedOutputStream(new FileOutputStream(args[0])));
    TProtocolFactory factory = (TProtocolFactory) Class.forName(args[1]).newInstance();
    TProtocol proto = factory.getProtocol(trans);
    Fixtures.compactProtoTestStruct.write(proto);
    trans.flush();
}
Example 87
Project: antlr-ide-master  File: AntlrTestCase.java View source code
void save(String content) throws IOException {
    this.input = content;
    File file = path.toFile();
    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
    }
    // path.toFile();
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    out.write(content.getBytes());
    out.close();
}
Example 88
Project: ariadne-repository-master  File: DownloadResourceServlet.java View source code
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String identifier = Utilities.escape(request.getParameter("objectid"));
    try {
        String mimetype = "application/octet-stream";
        log.info("Downloading object: " + identifier);
        DataHandler dataHandler = RetrieveContentFactory.retrieveContent(identifier);
        String fileName = RetrieveContentFactory.retrieveFileName(identifier);
        log.info("Datahandler is: " + dataHandler);
        response.setContentType(mimetype);
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName.replaceAll(" ", "_"));
        final BufferedInputStream input = new BufferedInputStream(dataHandler.getInputStream());
        final BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
        final int BUFFER_SIZE = 1024 * 4;
        final byte[] buffer = new byte[BUFFER_SIZE];
        while (true) {
            final int count = input.read(buffer, 0, BUFFER_SIZE);
            if (-1 == count) {
                break;
            }
            output.write(buffer, 0, count);
        }
        output.flush();
        dataHandler.getInputStream().close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Example 89
Project: AriadneRepository-master  File: DownloadResourceServlet.java View source code
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String identifier = Utilities.escape(request.getParameter("objectid"));
    try {
        String mimetype = "application/octet-stream";
        log.info("Downloading object: " + identifier);
        DataHandler dataHandler = RetrieveContentFactory.retrieveContent(identifier);
        String fileName = RetrieveContentFactory.retrieveFileName(identifier);
        log.info("Datahandler is: " + dataHandler);
        response.setContentType(mimetype);
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName.replaceAll(" ", "_"));
        final BufferedInputStream input = new BufferedInputStream(dataHandler.getInputStream());
        final BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
        final int BUFFER_SIZE = 1024 * 4;
        final byte[] buffer = new byte[BUFFER_SIZE];
        while (true) {
            final int count = input.read(buffer, 0, BUFFER_SIZE);
            if (-1 == count) {
                break;
            }
            output.write(buffer, 0, count);
        }
        output.flush();
        dataHandler.getInputStream().close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
Example 90
Project: audit4j-core-master  File: XMLConfigProvider.java View source code
/**
     * {@inheritDoc}
     * 
     * 
     */
@Override
public void generateConfig(T config, String filePath) throws ConfigurationException {
    XStream xstream = new XStream(new StaxDriver());
    xstream.alias("configuration", clazz);
    BufferedOutputStream stdout = null;
    try {
        stdout = new BufferedOutputStream(new FileOutputStream(filePath));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    xstream.marshal(config, new PrettyPrintWriter(new OutputStreamWriter(stdout)));
}
Example 91
Project: bnd-master  File: Sed.java View source code
public static void file2GzFile(String filenameIn, String searchPattern, String replacementPattern, String filenameOut) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filenameIn)));
    BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(filenameOut)));
    processObrFileInternal(reader, searchPattern, replacementPattern, out);
}
Example 92
Project: bubolo-master  File: PreferencesManager.java View source code
/**
	 * Serializes and saves the Preferences model to disk
	 * @param pm the Preferences model to save to disk
	 */
public void SavePreference(PreferencesModel pm) {
    try (OutputStream file = new FileOutputStream(UserInterface.PREFERENCES_FILENAME);
        OutputStream buffer = new BufferedOutputStream(file);
        ObjectOutput output = new ObjectOutputStream(buffer)) {
        output.writeObject(pm);
    } catch (IOException ex) {
        System.out.println("Error Saving File. " + ex);
    }
}
Example 93
Project: buckminster-master  File: ExportPreferences.java View source code
@Override
protected int internalRun(IProgressMonitor monitor) throws Exception {
    OutputStream output = null;
    File prefsFile = this.getFile();
    try {
        if (prefsFile == null)
            output = System.out;
        else
            output = new BufferedOutputStream(new FileOutputStream(prefsFile));
        Platform.getPreferencesService().exportPreferences(this.getNode(), this.getFilter(), output);
        return 0;
    } catch (IOException e) {
        throw new SimpleErrorExitException(NLS.bind(Messages.Unable_to_open_file_0, prefsFile));
    } finally {
        if (prefsFile != null)
            IOUtils.close(output);
    }
}
Example 94
Project: Canova-master  File: SVMRecordWriterTest.java View source code
@Test
public void testWriter() throws Exception {
    InputStream is = new ClassPathResource("iris.dat").getInputStream();
    assumeNotNull(is);
    File tmp = new File("iris.txt");
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmp));
    IOUtils.copy(is, bos);
    bos.flush();
    bos.close();
    InputSplit split = new FileSplit(tmp);
    tmp.deleteOnExit();
    RecordReader reader = new CSVRecordReader();
    List<Collection<Writable>> records = new ArrayList<>();
    reader.initialize(split);
    int count = 0;
    while (reader.hasNext()) {
        Collection<Writable> record = reader.next();
        records.add(record);
        assertEquals(5, record.size());
        records.add(record);
        count++;
    }
    assertEquals(150, count);
    File out = new File("iris_out.txt");
    out.deleteOnExit();
    RecordWriter writer = new SVMLightRecordWriter(out, true);
    for (Collection<Writable> record : records) writer.write(record);
    writer.close();
    RecordReader svmReader = new SVMLightRecordReader();
    InputSplit svmSplit = new FileSplit(out);
    svmReader.initialize(svmSplit);
    assertTrue(svmReader.hasNext());
    while (svmReader.hasNext()) {
        Collection<Writable> record = svmReader.next();
        records.add(record);
        assertEquals(5, record.size());
        records.add(record);
        count++;
    }
}
Example 95
Project: caxap-master  File: CompiledClass.java View source code
/*****************************************************************************
   * Dump the bytecode into a file whose matches the structure of the class
   * name, under the $root directory.
   */
public void dump(Path root) {
    String relative = name.replaceAll("\\.", Matcher.quoteReplacement(File.separator)) + ".class";
    File output = root.resolve(relative).toFile();
    try {
        FileUtils.create(output);
        OutputStream stream = new BufferedOutputStream(new FileOutputStream(output), bytecode.length);
        stream.write(bytecode);
        stream.close();
    } catch (IOException e) {
        throw new Error("I/O error when trying to dump bytecode for class " + name + " to file " + output + ".", e);
    }
}
Example 96
Project: cdo-master  File: ContainerPersistence.java View source code
public void saveElements(Collection<E> elements) throws IORuntimeException {
    OutputStream out = null;
    try {
        out = openOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(out));
        oos.writeObject(elements);
        oos.flush();
    } catch (IOException ex) {
        throw new IORuntimeException(ex);
    } finally {
        IOUtil.closeSilent(out);
    }
}
Example 97
Project: certificate-master  File: ZipBytes.java View source code
public static Map<String, byte[]> decompressing(byte[] file) {
    BufferedOutputStream dest = null;
    ZipEntry entry = null;
    Map<String, byte[]> files = new HashMap<String, byte[]>();
    InputStream in = new ByteArrayInputStream(file);
    ZipInputStream zipStream = new ZipInputStream(in);
    try {
        while ((entry = zipStream.getNextEntry()) != null) {
            int count;
            byte buf[] = new byte[BUFFER_SIZE];
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            dest = new BufferedOutputStream(outputStream, BUFFER_SIZE);
            while ((count = zipStream.read(buf, 0, BUFFER_SIZE)) != -1) {
                dest.write(buf, 0, count);
            }
            dest.flush();
            dest.close();
            files.put(entry.getName(), outputStream.toByteArray());
            zipStream.closeEntry();
        }
    } catch (IOException e) {
        new CertificateUtilException(e.getMessage(), e);
    }
    return files;
}
Example 98
Project: ciel-java-master  File: SWTeraSampler.java View source code
public void invoke(InputStream[] inputs, OutputStream[] outputs, String[] args) {
    int nBucketers = Integer.parseInt(args[0]);
    int nPartitions = Integer.parseInt(args[1]);
    int nRecordsExpected = Integer.parseInt(args[2]);
    int recordsBetweenBoundaries = nRecordsExpected / nPartitions;
    DataInputStream[] dis = new DataInputStream[nBucketers];
    for (int i = 0; i < nBucketers; i++) {
        dis[i] = new DataInputStream(new BufferedInputStream(inputs[i]));
    }
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(outputs[0]));
    TextPairIterator iter = null;
    try {
        iter = Merger.merge(dis);
    } catch (IOException e) {
        System.err.println("Exception during merge: " + e);
        System.exit(2);
    }
    try {
        int i = 1;
        int boundariesEmitted = 0;
        while ((boundariesEmitted < (nPartitions - 1)) && iter.next()) {
            Text key;
            if ((i % recordsBetweenBoundaries) == 0) {
                key = iter.getKey();
                key.write(dos);
                boundariesEmitted++;
            }
            i++;
        }
        dos.close();
        if (boundariesEmitted != (nPartitions - 1)) {
            System.err.printf("Emitted %d boundaries (expected %d), probably due to short input (got %d records, expected %d)\n", boundariesEmitted, nPartitions - 1, i, nRecordsExpected);
            System.exit(2);
        }
    } catch (IOException e) {
        System.err.println("Exception during iteration / writing: " + e);
        System.exit(2);
    }
}
Example 99
Project: clearnlp-master  File: IntHashSetTest.java View source code
@Test
public void test() throws Exception {
    IntHashSet set = new IntHashSet();
    set.add(1);
    set.add(2);
    set.add(1);
    set.add(3);
    int len = set.size();
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
    out.writeObject(set);
    out.close();
    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(bout.toByteArray())));
    set = (IntHashSet) in.readObject();
    in.close();
    assertEquals(len, set.size());
    assertTrue(set.contains(1));
    assertTrue(set.contains(2));
    assertTrue(set.contains(3));
    assertFalse(set.contains(0));
    assertFalse(set.contains(4));
}
Example 100
Project: Cloud9-master  File: CreateMetadata.java View source code
public static void GenerateMetadata(Path bitextPath, Path resultPath) throws IOException {
    System.out.println(bitextPath.toString());
    JobConf conf = new JobConf(CreateMetadata.class);
    FileSystem fileSys = FileSystem.get(conf);
    //SequenceFile.Reader[] x = SequenceFileOutputFormat.getReaders(conf, bitextPath);
    SequenceFile.Reader[] x = SequenceFileOutputFormat.getReaders(conf, new Path("/shared/bitexts/ar-en.ldc.10k/ar-en.10k.bitext"));
    WritableComparable key = new IntWritable();
    PhrasePair value = new PhrasePair();
    int sc = 0;
    int ec = 0;
    int fc = 0;
    try {
        for (SequenceFile.Reader r : x) while (r.next(key, value)) {
            sc = sc + 1;
            for (int word : value.getE().getWords()) if (word > ec)
                ec = word;
            for (int word : value.getF().getWords()) if (word > fc)
                fc = word;
        }
    } catch (IOException e) {
        throw new RuntimeException("IO exception: " + e.getMessage());
    }
    Metadata theMetadata = new Metadata(sc, ec, fc);
    ObjectOutputStream mdstream = new ObjectOutputStream(new BufferedOutputStream(FileSystem.get(conf).create(resultPath)));
    mdstream.writeObject(theMetadata);
    mdstream.close();
}
Example 101
Project: clusters-master  File: HttpUtils.java View source code
public static void downloadFileWithProgress(String fileUrl, String outputFilePath) throws IOException {
    String fileName = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
    URL url = new URL(fileUrl);
    HttpURLConnection httpURLConnection = (HttpURLConnection) (url.openConnection());
    long fileSize = httpURLConnection.getContentLength();
    // Create the parent output directory if it doesn't exis
    if (!new File(outputFilePath).getParentFile().isDirectory()) {
        new File(outputFilePath).getParentFile().mkdirs();
    }
    BufferedInputStream bufferedInputStream = new BufferedInputStream(httpURLConnection.getInputStream());
    FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream, 1024);
    byte[] data = new byte[1024];
    long downloadedFileSize = 0;
    Integer previousProgress = 0;
    int x = 0;
    while ((x = bufferedInputStream.read(data, 0, 1024)) >= 0) {
        downloadedFileSize += x;
        final int currentProgress = (int) (((double) downloadedFileSize / (double) fileSize) * 100d);
        if (!previousProgress.equals(currentProgress)) {
            LOG.info("HTTP: Download Status: Filename {} - {}% ({}/{})", fileName, currentProgress, downloadedFileSize, fileSize);
            previousProgress = currentProgress;
        }
        bufferedOutputStream.write(data, 0, x);
    }
    bufferedOutputStream.close();
    bufferedInputStream.close();
}