Example usage for java.io BufferedOutputStream flush

List of usage examples for java.io BufferedOutputStream flush

Introduction

In this page you can find the example usage for java.io BufferedOutputStream flush.

Prototype

@Override
public synchronized void flush() throws IOException 

Source Link

Document

Flushes this buffered output stream.

Usage

From source file:gtu.youtube.JavaYoutubeDownloader.java

private void downloadWithHttpClient(String userAgent, String downloadUrl, File outputfile) throws Throwable {
    HttpGet httpget2 = new HttpGet(downloadUrl);
    if (userAgent != null && userAgent.length() > 0) {
        httpget2.setHeader("User-Agent", userAgent);
    }//ww w . j  a va  2  s  .c o  m

    log.finer("Executing " + httpget2.getURI());
    HttpClient httpclient2 = new DefaultHttpClient();
    HttpResponse response2 = httpclient2.execute(httpget2);
    HttpEntity entity2 = response2.getEntity();
    if (entity2 != null && response2.getStatusLine().getStatusCode() == 200) {
        double length = entity2.getContentLength();
        if (length <= 0) {
            // Unexpected, but do not divide by zero
            length = 1;
        }
        InputStream instream2 = entity2.getContent();
        System.out.println("Writing " + commaFormatNoPrecision.format(length) + " bytes to " + outputfile);
        if (outputfile.exists()) {
            outputfile.delete();
        }
        BufferedOutputStream outstream = new BufferedOutputStream(new FileOutputStream(outputfile));
        System.out.println("outputfile " + outputfile);
        try {
            byte[] buffer = new byte[BUFFER_SIZE];
            double total = 0;
            int count = -1;
            int progress = 10;
            long start = System.currentTimeMillis();
            while ((count = instream2.read(buffer)) != -1) {
                total += count;
                int p = (int) ((total / length) * ONE_HUNDRED);
                if (p >= progress) {
                    long now = System.currentTimeMillis();
                    double s = (now - start) / 1000;
                    int kbpers = (int) ((total / KB) / s);
                    System.out.println(progress + "% (" + kbpers + "KB/s)");
                    progress += 10;
                }
                outstream.write(buffer, 0, count);
            }
            outstream.flush();
        } finally {
            outstream.close();
        }
        System.out.println("Done");
    }
}

From source file:com.fdt.sdl.admin.ui.action.UploadAction.java

public void extractZip(InputStream is) throws IOException {
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
    int BUFFER = 4096;
    BufferedOutputStream dest = null;
    ZipEntry entry;//from ww w.  j  av  a 2  s.c  o m
    while ((entry = zis.getNextEntry()) != null) {
        // System.out.println("Extracting: " +entry);
        // out.println(entry.getName());
        String entryPath = entry.getName();
        if (entryPath.indexOf('\\') >= 0) {
            entryPath = entryPath.replace('\\', File.separatorChar);
        }
        String destFilePath = WebserverStatic.getRootDirectory() + entryPath;
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        File f = new File(destFilePath);

        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        if (!f.exists()) {
            FileUtil.createNewFile(f);
            logger.info("creating file: " + f);
        } else {
            logger.info("already existing file: " + f);
            if (f.isDirectory()) {
                continue;
            }
        }

        FileOutputStream fos = new FileOutputStream(f);
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
    }
    zis.close();
}

From source file:com.android.tradefed.util.FileUtil.java

public static void extractTarGzip(File tarGzipFile, File destDir)
        throws FileNotFoundException, IOException, ArchiveException {
    GZIPInputStream gzipIn = null;
    ArchiveInputStream archivIn = null;/*from w w w . jav a 2s  .c  o  m*/
    BufferedInputStream buffIn = null;
    BufferedOutputStream buffOut = null;
    try {
        gzipIn = new GZIPInputStream(new BufferedInputStream(new FileInputStream(tarGzipFile)));
        archivIn = new ArchiveStreamFactory().createArchiveInputStream("tar", gzipIn);
        buffIn = new BufferedInputStream(archivIn);
        TarArchiveEntry entry = null;
        while ((entry = (TarArchiveEntry) archivIn.getNextEntry()) != null) {
            String entryName = entry.getName();
            String[] engtryPart = entryName.split("/");
            StringBuilder fullPath = new StringBuilder();
            fullPath.append(destDir.getAbsolutePath());
            for (String e : engtryPart) {
                fullPath.append(File.separator);
                fullPath.append(e);
            }
            File destFile = new File(fullPath.toString());
            if (entryName.endsWith("/")) {
                if (!destFile.exists())
                    destFile.mkdirs();
            } else {
                if (!destFile.exists())
                    destFile.createNewFile();
                buffOut = new BufferedOutputStream(new FileOutputStream(destFile));
                byte[] buf = new byte[8192];
                int len = 0;
                while ((len = buffIn.read(buf)) != -1) {
                    buffOut.write(buf, 0, len);
                }
                buffOut.flush();
            }
        }
    } finally {
        if (buffOut != null) {
            buffOut.close();
        }
        if (buffIn != null) {
            buffIn.close();
        }
        if (archivIn != null) {
            archivIn.close();
        }
        if (gzipIn != null) {
            gzipIn.close();
        }
    }

}

From source file:io.milton.httpclient.Host.java

/**
 *
 * @param path - the path to get, relative to the base path of the host
 * @param file - the file to write content to
 * @param listener/*from   ww w.ja va  2 s .co m*/
 * @throws IOException
 * @throws NotFoundException
 * @throws com.ettrema.httpclient.HttpException
 * @throws com.ettrema.httpclient.Utils.CancelledException
 * @throws NotAuthorizedException
 * @throws BadRequestException
 * @throws ConflictException
 */
public synchronized void doGet(Path path, final java.io.File file, ProgressListener listener)
        throws IOException, NotFoundException, io.milton.httpclient.HttpException, CancelledException,
        NotAuthorizedException, BadRequestException, ConflictException {
    LogUtils.trace(log, "doGet", path);
    if (fileSyncer != null) {
        fileSyncer.download(this, path, file, listener);
    } else {
        String url = this.buildEncodedUrl(path);
        transferService.get(url, new StreamReceiver() {
            @Override
            public void receive(InputStream in) throws IOException {
                OutputStream out = null;
                BufferedOutputStream bout = null;
                try {
                    out = FileUtils.openOutputStream(file);
                    bout = new BufferedOutputStream(out);
                    IOUtils.copy(in, bout);
                    bout.flush();
                } finally {
                    IOUtils.closeQuietly(bout);
                    IOUtils.closeQuietly(out);
                }

            }
        }, null, listener, newContext());
    }
}

From source file:org.catrobat.catroid.uitest.util.UiTestUtils.java

/**
 * saves a file into the project folder//from w  ww  .j  av  a2 s  . c o m
 * if project == null or "" file will be saved into Catroid folder
 *
 * @param project Folder where the file will be saved, this folder should exist
 * @param name    Name of the file
 * @param fileID  the id of the file --> needs the right context
 * @param context
 * @param type    type of the file: 0 = imagefile, 1 = soundfile
 * @return the file
 * @throws IOException
 */
public static File saveFileToProject(String project, String name, int fileID, Context context, FileTypes type) {

    boolean withChecksum = true;
    String filePath;
    if (project == null || project.equalsIgnoreCase("")) {
        filePath = Constants.DEFAULT_ROOT + "/";
    } else {
        switch (type) {
        case IMAGE:
            filePath = Constants.DEFAULT_ROOT + "/" + project + "/" + Constants.IMAGE_DIRECTORY + "/";
            break;
        case SOUND:
            filePath = Constants.DEFAULT_ROOT + "/" + project + "/" + Constants.SOUND_DIRECTORY + "/";
            break;
        case ROOT:
            filePath = Constants.DEFAULT_ROOT + "/" + project + "/";
            withChecksum = false;
            break;
        default:
            filePath = Constants.DEFAULT_ROOT + "/";
            break;
        }
    }
    BufferedInputStream in = new BufferedInputStream(context.getResources().openRawResource(fileID),
            Constants.BUFFER_8K);

    try {
        File file = new File(filePath + name);
        file.getParentFile().mkdirs();
        file.createNewFile();

        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file), Constants.BUFFER_8K);
        byte[] buffer = new byte[Constants.BUFFER_8K];
        int length = 0;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }

        in.close();
        out.flush();
        out.close();

        String checksum;
        if (withChecksum) {
            checksum = Utils.md5Checksum(file) + "_";
        } else {
            checksum = "";
        }

        File tempFile = new File(filePath + checksum + name);
        file.renameTo(tempFile);

        return tempFile;
    } catch (IOException e) {
        Log.e(TAG, "File handling error", e);
        return null;
    }
}

From source file:app.common.X3DViewer.java

/**
 * View an X3D file using an external X3DOM player
 *
 * @param filename/*from w  w w  . ja v  a 2  s  .  c o m*/
 * @throws IOException
 */
public static void viewX3DOM(String[] filename, float[] pos) throws IOException {
    // TODO: Make thread safe using tempDir
    String dest = "/tmp/";
    File dir = new File(dest);
    dir.mkdirs();

    String pf = "x3dom/x3dom.css";
    String dest_pf = dest + pf;
    File dest_file = new File(dest_pf);
    File src_file = new File("src/html/" + pf);
    if (!dest_file.exists()) {
        System.out.println("Copying file: " + src_file + " to dir: " + dest);
        FileUtils.copyFile(src_file, dest_file, true);
    }

    pf = "x3dom/x3dom.js";
    dest_pf = dest + pf;
    dest_file = new File(dest_pf);
    src_file = new File("src/html/" + pf);
    if (!dest_file.exists()) {
        System.out.println("Copying file: " + src_file + " to dir: " + dest);
        FileUtils.copyFile(src_file, dest_file, true);
    }
    File f = new File("/tmp/out.xhtml");
    FileOutputStream fos = new FileOutputStream(f);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    PrintStream ps = new PrintStream(bos);

    try {
        ps.println(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
        ps.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        ps.println("<head>");
        ps.println("<meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\" />");
        ps.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
        ps.println("<title>Ring Popper Demo</title>");
        //            ps.println("<link rel='stylesheet' type='text/css' href='http://www.x3dom.org/x3dom/release/x3dom.css'></link>");
        ps.println("<link rel='stylesheet' type='text/css' href='x3dom/x3dom.css'></link>");
        ps.println("</head>");
        ps.println("<body>");

        ps.println("<p class='case'>");
        ps.println(
                "<X3D profile='Immersive' showLog='true' showStats='true' version='3.0' height='600px' width='600px' y='0px' x='0px'>");
        // had to turn of isStaticHierarchy
        //            ps.println("<Scene isStaticHierarchy=\"true\" sortTrans=\"false\" doPickPass=\"false\" frustumCulling=\"false\">");
        ps.println("<Scene sortTrans=\"false\" doPickPass=\"false\" frustumCulling=\"false\">");
        //            ps.println("<Scene>");
        ps.println("<Background skyColor=\"1 1 1\" />");

        if (pos != null) {
            ps.println("<Viewpoint position='" + pos[0] + " " + pos[1] + " " + pos[2] + "' />");
        }
        for (int i = 0; i < filename.length; i++) {
            if (filename[i] != null) {
                ps.println("<Inline url='" + filename[i] + "' />");
            }
        }
        ps.println("</Scene>");
        ps.println("</X3D>");

        //            ps.println("<script type='text/javascript' src='http://www.x3dom.org/x3dom/release/x3dom.js'></script>");
        ps.println("<script type='text/javascript' src='x3dom/x3dom.js'></script>");

        ps.println("</p>");
        ps.println("</body></html>");
    } finally {
        bos.flush();
        bos.close();
        fos.close();
    }

    Desktop.getDesktop().browse(f.toURI());
}

From source file:mobi.dlys.android.core.net.http.handler.DownloadHttpResponseHandler.java

@Override
public void sendResponseMessage(HttpResponse response, HttpUriRequest request) {
    StatusLine status = response.getStatusLine();
    Header[] allHeaders = response.getAllHeaders();
    Header[] contentTypeHeaders = response.getHeaders("Content-Type");
    if (contentTypeHeaders.length != 1) {
        // malformed/ambiguous HTTP Header, ABORT!
        sendFailureMessage(new HttpResponseException(status.getStatusCode(),
                "None, or more than one, Content-Type Header found!"), mSavePath);
        return;//w  w  w  . j av  a2 s .  c o  m
    }
    // Header contentTypeHeader = contentTypeHeaders[0];
    // boolean foundAllowedContentType = false;
    // for (String anAllowedContentType : mAllowedContentTypes) {
    // if (Pattern.matches(anAllowedContentType,
    // contentTypeHeader.getValue())) {
    // foundAllowedContentType = true;
    // }
    // }
    // foundAllowedContentType = true;
    // if (!foundAllowedContentType) {
    // // Content-Type not in allowed list, ABORT!
    // sendFailureMessage(new HttpResponseException(status.getStatusCode(),
    // "Content-Type not allowed!"), mSavePath);
    // return;
    // }

    int responseCode = status.getStatusCode();
    if (responseCode != 200) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()),
                mSavePath);
        return;
    }

    HttpEntity temp = response.getEntity();
    if (null == temp) {
        return;
    }

    BufferedInputStream in = null;
    BufferedOutputStream out = null;
    long contentLength = temp.getContentLength();
    long loadedLength = 0;
    try {

        File file = new File(mSavePath);
        File parent = file.getParentFile();
        if (!parent.exists() && !parent.mkdirs()) {
            sendFailureMessage(new IOException("create new path failure!"), parent.getAbsolutePath());
            return;
        }
        if (!file.exists() && !file.createNewFile()) {
            sendFailureMessage(new IOException("create new file failure!"), mSavePath);
            return;
        }
        in = new BufferedInputStream(temp.getContent());
        out = new BufferedOutputStream(new FileOutputStream(mSavePath));
        int length = 8192;
        byte[] buffer = new byte[length];
        while (-1 != (length = in.read(buffer))) {
            out.write(buffer, 0, length);
            loadedLength += length;
            sendProgressChangeMessage(contentLength, loadedLength);
        }
    } catch (IOException e) {
        sendFailureMessage(e, mSavePath);
    } finally {
        try {
            if (null != out) {
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            sendFailureMessage(e, mSavePath);
        }
        try {
            if (null != in) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            sendFailureMessage(e, mSavePath);
        }
    }

    if (status.getStatusCode() < 300) {
        sendSuccessMessage(status.getStatusCode(), allHeaders, mSavePath);
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Copies all data from one stream to another*/
private void copyStreams(InputStream in, OutputStream out) throws IOException {
    BufferedInputStream inStream = new BufferedInputStream(in);
    BufferedOutputStream outStream = new BufferedOutputStream(out);
    //copy the contents to an output stream
    byte[] buffer = new byte[2048];
    int read = 0;
    //a read of 0 must be allowed, sometimes it takes time to
    //extract data from the input
    while (read != -1) {
        read = inStream.read(buffer);/*from w  ww.  j a va 2s.co  m*/
        if (read > 0) {
            outStream.write(buffer, 0, read);
        }
    }
    outStream.flush();
}

From source file:Main.java

public static boolean unzip(InputStream inputStream, String dest, boolean replaceIfExists) {

    final int BUFFER_SIZE = 4096;

    BufferedOutputStream bufferedOutputStream = null;

    boolean succeed = true;

    try {/*from www  . j a v  a  2s.co  m*/
        ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry zipEntry;

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {

            String zipEntryName = zipEntry.getName();

            //             if(!zipEntry.isDirectory()) {
            //                 File fil = new File(dest + zipEntryName);
            //                 fil.getParent()
            //             }

            // file exists ? delete ?
            File file2 = new File(dest + zipEntryName);

            if (file2.exists()) {
                if (replaceIfExists) {

                    try {
                        boolean b = deleteDir(file2);
                        if (!b) {
                            Log.e("Haggle", "Unzip failed to delete " + dest + zipEntryName);
                        } else {
                            Log.d("Haggle", "Unzip deleted " + dest + zipEntryName);
                        }
                    } catch (Exception e) {
                        Log.e("Haggle", "Unzip failed to delete " + dest + zipEntryName, e);
                    }
                }
            }

            // extract
            File file = new File(dest + zipEntryName);

            if (file.exists()) {

            } else {
                if (zipEntry.isDirectory()) {
                    file.mkdirs();
                    chmod(file, 0755);

                } else {

                    // create parent file folder if not exists yet
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                        chmod(file.getParentFile(), 0755);
                    }

                    byte buffer[] = new byte[BUFFER_SIZE];
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE);
                    int count;

                    while ((count = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
                        bufferedOutputStream.write(buffer, 0, count);
                    }

                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                }
            }

            // enable standalone python
            if (file.getName().endsWith(".so") || file.getName().endsWith(".xml")
                    || file.getName().endsWith(".py") || file.getName().endsWith(".pyc")
                    || file.getName().endsWith(".pyo")) {
                chmod(file, 0755);
            }

            Log.d("Haggle", "Unzip extracted " + dest + zipEntryName);
        }

        zipInputStream.close();

    } catch (FileNotFoundException e) {
        Log.e("Haggle", "Unzip error, file not found", e);
        succeed = false;
    } catch (Exception e) {
        Log.e("Haggle", "Unzip error: ", e);
        succeed = false;
    }

    return succeed;
}

From source file:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Send a file via HTTP POST with basic authentication.
 * /* www  . j ava  2s .c o m*/
 * @param urlStr the server url to POST to.
 * @param file the file to send.
 * @param user the user or <code>null</code>.
 * @param password the password or <code>null</code>.
 * @return the return string from the POST.
 * @throws Exception
 */
public static String sendFilePost(String urlStr, File file, String user, String password) throws Exception {
    BufferedOutputStream wr = null;
    FileInputStream fis = null;
    HttpURLConnection conn = null;
    try {
        fis = new FileInputStream(file);
        long fileSize = file.length();
        // Authenticator.setDefault(new Authenticator(){
        // protected PasswordAuthentication getPasswordAuthentication() {
        // return new PasswordAuthentication("test", "test".toCharArray());
        // }
        // });
        conn = makeNewConnection(urlStr);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // conn.setChunkedStreamingMode(0);
        conn.setUseCaches(true);

        // conn.setRequestProperty("Accept-Encoding", "gzip ");
        // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Type", "application/x-zip-compressed");
        // conn.setRequestProperty("Content-Length", "" + fileSize);
        // conn.setRequestProperty("Connection", "Keep-Alive");

        if (user != null && password != null) {
            conn.setRequestProperty("Authorization", getB64Auth(user, password));
        }
        conn.connect();

        wr = new BufferedOutputStream(conn.getOutputStream());
        long bufferSize = Math.min(fileSize, maxBufferSize);

        if (GPLog.LOG)
            GPLog.addLogEntry(TAG, "BUFFER USED: " + bufferSize);
        byte[] buffer = new byte[(int) bufferSize];
        int bytesRead = fis.read(buffer, 0, (int) bufferSize);
        long totalBytesWritten = 0;
        while (bytesRead > 0) {
            wr.write(buffer, 0, (int) bufferSize);
            totalBytesWritten = totalBytesWritten + bufferSize;
            if (totalBytesWritten >= fileSize)
                break;

            bufferSize = Math.min(fileSize - totalBytesWritten, maxBufferSize);
            bytesRead = fis.read(buffer, 0, (int) bufferSize);
        }
        wr.flush();

        String responseMessage = conn.getResponseMessage();

        if (GPLog.LOG)
            GPLog.addLogEntry(TAG, "POST RESPONSE: " + responseMessage);
        return responseMessage;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (wr != null)
            wr.close();
        if (fis != null)
            fis.close();
        if (conn != null)
            conn.disconnect();
    }
}