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:org.apache.torque.util.BasePeer.java

/**
 * Converts a hashtable to a byte array for storage/serialization.
 *
 * @param hash The Hashtable to convert.
 * @return A byte[] with the converted Hashtable.
 * @exception TorqueException//from   w  w  w. j a  v  a2s . c  om
 */
public static byte[] hashtableToByteArray(Hashtable hash) throws TorqueException {
    Hashtable saveData = new Hashtable(hash.size());
    String key = null;
    Object value = null;
    byte[] byteArray = null;

    Iterator keys = hash.keySet().iterator();
    while (keys.hasNext()) {
        key = (String) keys.next();
        value = hash.get(key);
        if (value instanceof Serializable) {
            saveData.put(key, value);
        }
    }

    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    ObjectOutputStream out = null;
    try {
        // These objects are closed in the finally.
        baos = new ByteArrayOutputStream();
        bos = new BufferedOutputStream(baos);
        out = new ObjectOutputStream(bos);

        out.writeObject(saveData);
        out.flush();
        bos.flush();
        byteArray = baos.toByteArray();
    } catch (Exception e) {
        throw new TorqueException(e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ignored) {
            }
        }

        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ignored) {
            }
        }

        if (baos != null) {
            try {
                baos.close();
            } catch (IOException ignored) {
            }
        }
    }
    return byteArray;
}

From source file:com.glaf.core.util.FtpUtils.java

/**
 * /*from ww w  .j ava  2  s .c om*/
 * 
 * @param remoteFile
 *            FTP"/"
 */
public static byte[] getBytes(String remoteFile) {
    byte[] bytes = null;
    InputStream in = null;
    ByteArrayOutputStream out = null;
    BufferedOutputStream bos = null;
    try {
        if (remoteFile.startsWith("/") && remoteFile.indexOf("/") > 0) {
            changeToDirectory(remoteFile);
            remoteFile = remoteFile.substring(remoteFile.lastIndexOf("/") + 1, remoteFile.length());
        }
        // ?
        getFtpClient().enterLocalPassiveMode();
        // ?
        getFtpClient().setFileType(FTP.BINARY_FILE_TYPE);
        FTPFile[] files = getFtpClient().listFiles(new String(remoteFile.getBytes("GBK"), "ISO-8859-1"));
        if (files.length != 1) {
            logger.warn("remote file is not exists");
            return null;
        }
        long lRemoteSize = files[0].getSize();

        out = new ByteArrayOutputStream();
        bos = new BufferedOutputStream(out);
        in = getFtpClient().retrieveFileStream(new String(remoteFile.getBytes("GBK"), "ISO-8859-1"));
        byte[] buff = new byte[4096];
        long step = lRemoteSize / 100;
        if (step == 0) {
            step = 1;
        }
        long progress = 0;
        long localSize = 0L;
        int c;
        while ((c = in.read(buff)) != -1) {
            out.write(buff, 0, c);
            localSize += c;
            long nowProgress = localSize / step;
            if (nowProgress > progress) {
                progress = nowProgress;
                if (progress % 10 == 0) {
                    logger.debug("download progress:" + progress);
                }
            }
        }
        out.flush();
        bos.flush();
        bytes = out.toByteArray();
    } catch (Exception ex) {
        ex.printStackTrace();
        logger.error("download error", ex);
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(in);
        IOUtils.closeStream(out);
    }
    return bytes;
}

From source file:net.ytbolg.mcxa.ForgeCheck.java

void downloadFile(String remoteFilePath, String localFilePath) {
    URL urlfile = null;/*from w  w w  .ja v a 2 s .c o  m*/
    HttpURLConnection httpUrl = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    File f = new File(localFilePath);
    File xxxx = new File(f.getParent());
    xxxx.mkdirs();

    //      f.mkdirs();
    try {
        urlfile = new URL(remoteFilePath);
        httpUrl = (HttpURLConnection) urlfile.openConnection();
        httpUrl.connect();
        j.setMaximum(httpUrl.getContentLength());
        j.setValue(0);
        bis = new BufferedInputStream(httpUrl.getInputStream());
        bos = new BufferedOutputStream(new FileOutputStream(f));
        int len = 2048;
        byte[] b = new byte[len];
        int i = 0;
        while ((len = bis.read(b)) != -1) {
            i = i + len;
            j.setValue(i);
            l.setText(i / 1024 + "/" + (httpUrl.getContentLength() / 1024) + "KB");
            bos.write(b, 0, len);
        }
        bos.flush();
        bis.close();
        httpUrl.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            bis.close();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:InstallJars.java

/** Copy a zip entry. */
protected void copyEntry(String target, ZipInputStream zis, ZipEntry ze) throws IOException {
    String name = ze.getName();//from   w w  w . j  av  a  2 s.co m
    boolean isDir = false;
    if (name.endsWith("/")) {
        name = name.substring(0, name.length() - 1);
        isDir = true;
    }
    String path = target + File.separator + name;
    path = path.replace('\\', '/');
    String mod = ze.getSize() > 0 ? ("[" + ze.getCompressedSize() + ":" + ze.getSize() + "]") : "";
    print("Expanding " + ze + mod + " to " + path);
    prepDirs(path, isDir);
    if (!isDir) {
        BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(path),
                BLOCK_SIZE * BLOCK_COUNT);
        try {
            byte[] buf = new byte[bufferSize];
            for (int size = zis.read(buf, 0, buf.length), count = 0; size >= 0; size = zis.read(buf, 0,
                    buf.length), count++) {
                // if (count % 4 == 0) print(".");
                os.write(buf, 0, size);
            }
        } finally {
            try {
                os.flush();
                os.close();
            } catch (IOException ioe) {
            }
        }
    }
    println();
}

From source file:it.geosolutions.geobatch.services.rest.impl.RESTFileBasedFlowServiceImpl.java

/**
 * @see it.geosolutions.geobatch.services.rest.RESTFlowService#run(java.lang.String, java.lang.Boolean, byte[])
 *///from  ww w . java2 s  . c  o  m
@Override
public String run(String flowId, Boolean fastfail, String fileName, byte[] data)
        throws BadRequestRestEx, InternalErrorRestEx {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Running instance of flow " + flowId);
    }

    final FileBasedFlowManager flowMan = getAuthFlowManager(flowId);
    if (flowMan == null) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Flow not found: " + flowId);
        }
        throw new NotFoundRestEx("Flow not found: " + flowId);
    }

    OutputStream os = null;
    BufferedOutputStream bos = null;
    File eventFile = null;

    try {
        if (fileName == null || fileName.isEmpty()) {
            fileName = "inputConfig" + System.currentTimeMillis() + ".tmp";
        }

        // TODO: reconsider the usage of this temp dir: the consumer.flowinstancetempdir should be used,
        // or the watchdir. Creating such a dir will never be disposed automatically.
        eventFile = new File(flowMan.getFlowTempDir() + File.separator + fileName.toString());
        LOGGER.warn("Creating temp input file " + eventFile + " . THIS FILE SHOULD BE PLACED SOMEWHERE ELSE");

        os = new FileOutputStream(eventFile);
        bos = new BufferedOutputStream(os);
        bos.write(data);
        bos.flush();
    } catch (Exception e) {
        throw new InternalErrorRestEx(e.getLocalizedMessage());
    } finally {
        IOUtils.closeQuietly(bos);
        IOUtils.closeQuietly(os);
    }

    final FlowRunner fr = new FlowRunner(flowMan, dataDirHandler);
    FileBasedEventConsumer consumer = null;
    try {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Creating new consumer for flow " + flowId);
        }
        consumer = fr.createConsumer();
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Starting the consumer " + flowId + "::" + consumer.getId());
        }

        fr.runConsumer(consumer.getId(), Collections.singletonList(eventFile));
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new InternalErrorRestEx(e.getMessage());
    }
    return consumer.getId();
}

From source file:hudson.gridmaven.gridlayer.HadoopInstance.java

/**
 * This method decompress filesystem structure from HDFS archive
 *///  ww w. j  a va2s .  co m
public void getAndUntar(String src, String targetPath) throws FileNotFoundException, IOException {
    BufferedOutputStream dest = null;
    InputStream tarArchiveStream = new FSDataInputStream(fs.open(new Path(src)));
    TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(tarArchiveStream));
    TarArchiveEntry entry = null;
    try {
        while ((entry = tis.getNextTarEntry()) != null) {
            int count;
            File outputFile = new File(targetPath, entry.getName());

            if (entry.isDirectory()) { // entry is a directory
                if (!outputFile.exists()) {
                    outputFile.mkdirs();
                }
            } else { // entry is a file
                byte[] data = new byte[BUFFER_MAX];
                FileOutputStream fos = new FileOutputStream(outputFile);
                dest = new BufferedOutputStream(fos, BUFFER_MAX);
                while ((count = tis.read(data, 0, BUFFER_MAX)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dest != null) {
            dest.flush();
            dest.close();
        }
        tis.close();
    }
}

From source file:com.zenika.dorm.importer.test.MavenRepositoryGenerator.java

private void generateChecksum(File file, File fileChecksum, String type) {
    FileOutputStream outputStream = null;
    BufferedOutputStream bufferedOutputStream = null;

    FileInputStream inputStream = null;
    BufferedInputStream bufferedInputStream = null;
    try {//from w  w  w  .  ja  v a 2s. c o  m
        MessageDigest digest = MessageDigest.getInstance(type);

        outputStream = new FileOutputStream(fileChecksum);
        bufferedOutputStream = new BufferedOutputStream(outputStream);

        inputStream = new FileInputStream(file);
        bufferedInputStream = new BufferedInputStream(inputStream);
        byte[] dataBytes = new byte[1024];
        int nread = 0;

        while ((nread = bufferedInputStream.read(dataBytes)) != -1) {
            digest.update(dataBytes, 0, nread);
        }

        byte[] byteDigested = digest.digest();

        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < byteDigested.length; i++) {
            sb.append(Integer.toString((byteDigested[i] & 0xff) + 0x100, 16).substring(1));
        }

        bufferedOutputStream.write(sb.toString().getBytes());
        bufferedOutputStream.flush();
    } catch (NoSuchAlgorithmException e) {
        throw new CoreException("Unable to digest this file: " + file, e);
    } catch (FileNotFoundException e) {
        throw new CoreException("Unable to digest this file: " + file, e);
    } catch (IOException e) {
        throw new CoreException("Unable to digest this file: " + file, e);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(bufferedInputStream);
        IOUtils.closeQuietly(bufferedOutputStream);
    }
}

From source file:org.cruk.seq.TrimFastq.java

/**
 * Writes an XML file containing a summary of the trimming.
 *
 * @param trimLength the length to which sequences were trimmed.
 * @param minLength the smallest sequence length
 * @param maxLength the largest sequence length
 *///  w  ww.  j a va 2 s .co m
private void writeSummary(int trimLength, int minLength, int maxLength) {
    if (summaryFilename == null)
        return;

    BufferedOutputStream outputStream = null;
    try {
        outputStream = new BufferedOutputStream(new FileOutputStream(summaryFilename));
    } catch (IOException e) {
        error("Error creating file " + summaryFilename);
    }

    try {
        Element root = new Element("TrimmingSummary");

        Element element = new Element("TrimLength");
        element.appendChild(Integer.toString(trimLength));
        root.appendChild(element);

        element = new Element("MinimumSequenceLength");
        element.appendChild(Integer.toString(minLength));
        root.appendChild(element);

        element = new Element("MaximumSequenceLength");
        element.appendChild(Integer.toString(maxLength));
        root.appendChild(element);

        Document document = new Document(root);

        Serializer serializer;
        serializer = new Serializer(outputStream, "ISO-8859-1");
        serializer.setIndent(2);
        serializer.setMaxLength(64);
        serializer.setLineSeparator("\n");
        serializer.write(document);

        outputStream.flush();
    } catch (UnsupportedEncodingException e) {
        error(e);
    } catch (IOException e) {
        error("Error writing summary XML file");
    } finally {
        try {
            outputStream.close();
        } catch (IOException e) {
            error("Error closing file " + summaryFilename);
        }
    }
}

From source file:com.ichi2.libanki.Utils.java

public static boolean unzipFiles(ZipFile zipFile, String targetDirectory, String[] zipEntries,
        HashMap<String, String> zipEntryToFilenameMap) {
    byte[] buf = new byte[FILE_COPY_BUFFER_SIZE];
    File dir = new File(targetDirectory);
    if (!dir.exists() && !dir.mkdirs()) {
        Timber.e("Utils.unzipFiles: Could not create target directory: " + targetDirectory);
        return false;
    }/*  w w  w  .jav  a2  s  .  c o m*/
    if (zipEntryToFilenameMap == null) {
        zipEntryToFilenameMap = new HashMap<String, String>();
    }
    BufferedInputStream zis = null;
    BufferedOutputStream bos = null;
    try {
        for (String requestedEntry : zipEntries) {
            ZipEntry ze = zipFile.getEntry(requestedEntry);
            if (ze != null) {
                String name = ze.getName();
                if (zipEntryToFilenameMap.containsKey(name)) {
                    name = zipEntryToFilenameMap.get(name);
                }
                File destFile = new File(dir, name);
                File parentDir = destFile.getParentFile();
                if (!parentDir.exists() && !parentDir.mkdirs()) {
                    return false;
                }
                if (!ze.isDirectory()) {
                    Timber.i("uncompress %s", name);
                    zis = new BufferedInputStream(zipFile.getInputStream(ze));
                    bos = new BufferedOutputStream(new FileOutputStream(destFile), FILE_COPY_BUFFER_SIZE);
                    int n;
                    while ((n = zis.read(buf, 0, FILE_COPY_BUFFER_SIZE)) != -1) {
                        bos.write(buf, 0, n);
                    }
                    bos.flush();
                    bos.close();
                    zis.close();
                }
            }
        }
    } catch (IOException e) {
        Timber.e(e, "Utils.unzipFiles: Error while unzipping archive.");
        return false;
    } finally {
        try {
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            Timber.e(e, "Utils.unzipFiles: Error while closing output stream.");
        }
        try {
            if (zis != null) {
                zis.close();
            }
        } catch (IOException e) {
            Timber.e(e, "Utils.unzipFiles: Error while closing zip input stream.");
        }
    }
    return true;
}

From source file:edu.jhu.cvrg.ceptools.main.SearchPubs.java

public void downloadFile(String filename, String filetype) {

    String contentType = "application/zip";

    if (filetype.equals("abf")) {
        contentType = "text/abf";
    }//from ww w  .j a v  a2s.  c  o  m

    FacesContext facesContext = (FacesContext) FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    PortletResponse portletResponse = (PortletResponse) externalContext.getResponse();
    HttpServletResponse response = PortalUtil.getHttpServletResponse(portletResponse);

    File file = new File(selecteddownloadfile.getFilelocation(), filename);
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        input = new BufferedInputStream(new FileInputStream(file), 10240);

        response.reset();
        response.setHeader("Content-Type", contentType);
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.flushBuffer();
        output = new BufferedOutputStream(response.getOutputStream(), 10240);

        byte[] buffer = new byte[10240];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        output.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            output.close();
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    facesContext.responseComplete();

}