Example usage for java.io BufferedOutputStream write

List of usage examples for java.io BufferedOutputStream write

Introduction

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

Prototype

@Override
public synchronized void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this buffered output stream.

Usage

From source file:com.arcusys.liferay.vaadinplugin.util.ControlPanelPortletUtil.java

/**
 * Extracts the jarEntry from the jarFile to the target directory.
 *
 * @param jarFile// ww w  . j  a  va 2 s . c  o m
 * @param jarEntry
 * @param targetDir
 * @return true if extraction was successful, false otherwise
 */
public static boolean extractJarEntry(JarFile jarFile, JarEntry jarEntry, String targetDir) {
    boolean extractSuccessful = false;
    File file = new File(targetDir);
    if (!file.exists()) {
        file.mkdir();
    }
    if (jarEntry != null) {
        InputStream inputStream = null;
        try {
            inputStream = jarFile.getInputStream(jarEntry);
            file = new File(targetDir + jarEntry.getName());
            if (jarEntry.isDirectory()) {
                file.mkdir();
            } else {
                int size;
                byte[] buffer = new byte[2048];

                FileOutputStream fileOutputStream = new FileOutputStream(file);
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream,
                        buffer.length);

                try {
                    while ((size = inputStream.read(buffer, 0, buffer.length)) != -1) {
                        bufferedOutputStream.write(buffer, 0, size);
                    }
                    bufferedOutputStream.flush();
                } finally {
                    bufferedOutputStream.close();
                }
            }
            extractSuccessful = true;
        } catch (Exception e) {
            log.warn(e);
        } finally {
            close(inputStream);
        }
    }
    return extractSuccessful;
}

From source file:com.dnielfe.manager.utils.SimpleUtils.java

/**
 * /*from w  w w. j  av a2 s.c  o  m*/
 * @param old
 *            the file to be copied/ moved
 * @param newDir
 *            the directory to copy/move the file to
 */
public static void copyToDirectory(String old, String newDir) {
    File old_file = new File(old);
    File temp_dir = new File(newDir);
    byte[] data = new byte[BUFFER];
    int read = 0;

    if (old_file.isFile() && temp_dir.isDirectory() && temp_dir.canWrite()) {
        String file_name = old.substring(old.lastIndexOf("/"), old.length());
        File cp_file = new File(newDir + file_name);

        try {
            BufferedOutputStream o_stream = new BufferedOutputStream(new FileOutputStream(cp_file));
            BufferedInputStream i_stream = new BufferedInputStream(new FileInputStream(old_file));

            while ((read = i_stream.read(data, 0, BUFFER)) != -1)
                o_stream.write(data, 0, read);

            o_stream.flush();
            i_stream.close();
            o_stream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    } else if (old_file.isDirectory() && temp_dir.isDirectory() && temp_dir.canWrite()) {
        String files[] = old_file.list();
        String dir = newDir + old.substring(old.lastIndexOf("/"), old.length());
        int len = files.length;

        if (!new File(dir).mkdir())
            return;

        for (int i = 0; i < len; i++)
            copyToDirectory(old + "/" + files[i], dir);

    } else if (old_file.isFile() && !temp_dir.canWrite() && SimpleExplorer.rootAccess) {
        RootCommands.moveCopyRoot(old, newDir);
    } else if (!temp_dir.canWrite())
        return;

    return;
}

From source file:com.geewhiz.pacify.utils.ArchiveUtils.java

private static Map<String, File> extractFiles(File archive, String archiveType, String searchFor,
        Boolean isRegExp) {/* w w w.j  a v  a2s . c  om*/
    Map<String, File> result = new HashMap<String, File>();

    ArchiveInputStream ais = null;
    try {
        ArchiveStreamFactory factory = new ArchiveStreamFactory();

        ais = factory.createArchiveInputStream(archiveType, new FileInputStream(archive));

        ArchiveEntry entry;
        while ((entry = ais.getNextEntry()) != null) {
            if (isRegExp) {
                if (!matches(entry.getName(), searchFor)) {
                    continue;
                }
            } else if (!searchFor.equals(entry.getName())) {
                continue;
            }

            File physicalFile = FileUtils.createEmptyFileWithSamePermissions(archive,
                    archive.getName() + "!" + Paths.get(entry.getName()).getFileName().toString() + "_");

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(physicalFile));

            byte[] content = new byte[2048];

            int len;
            while ((len = ais.read(content)) != -1) {
                bos.write(content, 0, len);
            }

            bos.close();
            content = null;

            result.put(entry.getName(), physicalFile);
        }
    } catch (ArchiveException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(ais);
    }

    return result;
}

From source file:net.duckling.ddl.util.FileUtil.java

/**
 * Brief Intro Here/*from   ww  w  .j  a v  a 2 s.co m*/
 * ?
 * @param
 */
public static void copyFile(File sourceFile, File targetFile) throws IOException {
    // ?
    FileInputStream input = new FileInputStream(sourceFile);
    BufferedInputStream inBuff = new BufferedInputStream(input);

    // ?
    FileOutputStream output = new FileOutputStream(targetFile);
    BufferedOutputStream outBuff = new BufferedOutputStream(output);

    // 
    byte[] b = new byte[1024 * 5];
    int len;
    while ((len = inBuff.read(b)) != -1) {
        outBuff.write(b, 0, len);
    }
    // ?
    outBuff.flush();

    // ?
    inBuff.close();
    outBuff.close();
    output.close();
    input.close();
}

From source file:org.ametro.util.WebUtil.java

public static void downloadFileUnchecked(Object context, URI uri, File file, IDownloadListener listener)
        throws Exception {
    BufferedInputStream strm = null;
    if (listener != null) {
        listener.onBegin(context, file);
    }//from w  w w .  j  ava2s  .  c om
    try {
        HttpClient client = ApplicationEx.getInstance().getHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(uri);
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            long total = (int) entity.getContentLength();
            long position = 0;

            if (file.exists()) {
                file.delete();
            }

            BufferedInputStream in = null;
            BufferedOutputStream out = null;
            try {
                in = new BufferedInputStream(entity.getContent());
                out = new BufferedOutputStream(new FileOutputStream(file));
                byte[] bytes = new byte[2048];
                for (int c = in.read(bytes); c != -1; c = in.read(bytes)) {
                    out.write(bytes, 0, c);
                    position += c;
                    if (listener != null) {
                        if (!listener.onUpdate(context, position, total)) {
                            throw new DownloadCanceledException();
                        }
                    }
                }

            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (Exception e) {
                    }
                }
            }
            if (listener != null) {
                listener.onDone(context, file);
            }
        } else {
            String message = "Failed to download URL " + uri.toString() + " due error " + status.getStatusCode()
                    + " " + status.getReasonPhrase();
            throw new Exception(message);
        }
    } finally {
        if (strm != null) {
            try {
                strm.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.ibm.amc.FileManager.java

public static File decompress(URI temporaryFileUri) {
    final File destination = new File(getUploadDirectory(), temporaryFileUri.getSchemeSpecificPart());
    if (!destination.mkdirs()) {
        throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR, "CWZBA2001E_DIRECTORY_CREATION_FAILED",
                destination.getPath());//from  ww  w.  java 2  s. c  o m
    }

    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(getFileForUri(temporaryFileUri));

        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File newDirOrFile = new File(destination, entry.getName());
            if (newDirOrFile.getParentFile() != null && !newDirOrFile.getParentFile().exists()) {
                if (!newDirOrFile.getParentFile().mkdirs()) {
                    throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR,
                            "CWZBA2001E_DIRECTORY_CREATION_FAILED", newDirOrFile.getParentFile().getPath());
                }
            }
            if (entry.isDirectory()) {
                if (!newDirOrFile.mkdir()) {
                    throw new AmcRuntimeException(Status.INTERNAL_SERVER_ERROR,
                            "CWZBA2001E_DIRECTORY_CREATION_FAILED", newDirOrFile.getPath());
                }
            } else {
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int size;
                byte[] buffer = new byte[ZIP_BUFFER];
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newDirOrFile),
                        ZIP_BUFFER);
                while ((size = bis.read(buffer, 0, ZIP_BUFFER)) != -1) {
                    bos.write(buffer, 0, size);
                }
                bos.flush();
                bos.close();
                bis.close();
            }
        }
    } catch (Exception e) {
        throw new AmcRuntimeException(e);
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                logger.debug("decompress", "close failed with " + e);
            }
        }
    }

    return destination;
}

From source file:de.suse.swamp.util.FileUtils.java

/**
 * Decompress the provided Stream to "targetPath"
 *///from  w  w w .  j a  v a2 s.c o m
public static void uncompress(InputStream inputFile, String targetPath) throws Exception {
    ZipInputStream zin = new ZipInputStream(new BufferedInputStream(inputFile));
    BufferedOutputStream dest = null;
    ZipEntry entry;
    while ((entry = zin.getNextEntry()) != null) {
        int count;
        byte data[] = new byte[2048];
        // write the files to the disk
        if (entry.isDirectory()) {
            org.apache.commons.io.FileUtils.forceMkdir(new File(targetPath + "/" + entry.getName()));
        } else {
            FileOutputStream fos = new FileOutputStream(targetPath + "/" + entry.getName());
            dest = new BufferedOutputStream(fos, 2048);
            while ((count = zin.read(data, 0, 2048)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
    }
}

From source file:fr.landel.utils.io.InternalFileSystemUtils.java

/**
 * Copy a file./*from   www . ja v a2 s  .co m*/
 * 
 * @param src
 *            The source file name
 * @param dest
 *            The destination file name
 * @param removeSource
 *            Remove the source after copy
 * @throws IOException
 *             Exception thrown if problems occurs during coping
 */
protected static void copyFile(final File src, final File dest, final boolean removeSource) throws IOException {
    int bufferReadSize;
    final byte[] buffer = new byte[BUFFER_SIZE];

    final File target;
    if (dest.isDirectory()) {
        target = new File(dest, src.getName());
    } else {
        target = dest;
    }

    if (InternalFileSystemUtils.createDirectory(target.getParentFile())) {
        if (!src.getAbsolutePath().equals(dest.getAbsolutePath())) {
            final BufferedInputStream bis = IOStreamUtils.createBufferedInputStream(src);
            final BufferedOutputStream bos = IOStreamUtils.createBufferedOutputStream(target);

            while ((bufferReadSize = bis.read(buffer, 0, BUFFER_SIZE)) >= 0) {
                bos.write(buffer, 0, bufferReadSize);
            }

            CloseableManager.close(target);
            CloseableManager.close(src);

            if (removeSource && !src.delete()) {
                throw new IOException("Cannot remove the source file");
            }
        }
    } else {
        throw new FileNotFoundException("destination directory doesn't exist and cannot be created");
    }
}

From source file:com.sangupta.jerry.unsafe.UnsafeMemoryUtils.java

public static void writeToFile(UnsafeMemory memory, File file) throws IOException {
    FileOutputStream stream = null;
    BufferedOutputStream boss = null;
    try {/*from w ww .j  av a2 s. c  o m*/
        final byte[] bytes = memory.getBuffer();
        final int length = memory.getPosition();

        stream = new FileOutputStream(file);
        boss = new BufferedOutputStream(stream);

        int CHUNK_SIZE = 1 << 20;
        int chunks = length / CHUNK_SIZE;
        int extra = length % CHUNK_SIZE;
        if (extra > 0) {
            chunks++;
        }

        for (int ki = 0; ki < chunks; ki++) {
            int delta = CHUNK_SIZE;
            if ((ki + 1) == chunks) {
                delta = extra;
            }
            boss.write(bytes, ki * CHUNK_SIZE, delta);
        }
    } catch (IOException e) {
        throw new IOException("Unable to write bytes to disk", e);
    } finally {
        IOUtils.closeQuietly(boss);
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.ametro.util.WebUtil.java

public static void downloadFile(Object context, URI uri, File file, boolean reuse, IDownloadListener listener) {
    BufferedInputStream strm = null;
    if (listener != null) {
        listener.onBegin(context, file);
    }/*from ww  w  .jav a2s.  co m*/
    try {
        HttpClient client = ApplicationEx.getInstance().getHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(uri);
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            long total = (int) entity.getContentLength();
            long position = 0;
            if (!(file.exists() && reuse && file.length() == total)) {
                if (file.exists()) {
                    file.delete();
                }
                BufferedInputStream in = null;
                BufferedOutputStream out = null;
                try {
                    in = new BufferedInputStream(entity.getContent());
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    byte[] bytes = new byte[2048];
                    for (int c = in.read(bytes); c != -1; c = in.read(bytes)) {
                        out.write(bytes, 0, c);
                        position += c;
                        if (listener != null) {
                            if (!listener.onUpdate(context, position, total)) {
                                throw new DownloadCanceledException();
                            }
                        }
                    }

                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (Exception e) {
                        }
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (Exception e) {
                        }
                    }
                }
            }
            if (listener != null) {
                listener.onDone(context, file);
            }
        } else {
            String message = "Failed to download URL " + uri.toString() + " due error " + status.getStatusCode()
                    + " " + status.getReasonPhrase();
            throw new Exception(message);
        }
    } catch (DownloadCanceledException ex) {
        if (listener != null) {
            listener.onCanceled(context, file);
        }
    } catch (Exception ex) {
        if (listener != null) {
            listener.onFailed(context, file, ex);
        }
    } finally {
        if (strm != null) {
            try {
                strm.close();
            } catch (IOException ex) {
            }
        }
    }
}