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:net.amigocraft.mpt.util.MiscUtil.java

public static boolean unzip(ZipFile zip, File dest, List<String> files) throws MPTException {
    boolean returnValue = true;
    try {/*from ww  w.j a  va  2s  .co m*/
        List<String> existingDirs = new ArrayList<>();
        Enumeration<? extends ZipEntry> en = zip.entries();
        entryLoop: while (en.hasMoreElements()) {
            ZipEntry entry = en.nextElement();
            String name = entry.getName().startsWith("./")
                    ? entry.getName().substring(2, entry.getName().length())
                    : entry.getName();
            File file = new File(dest, name);
            if (entry.isDirectory()) {
                if (file.exists()) {
                    if (DISALLOW_MERGE) {
                        existingDirs.add(name);
                        if (VERBOSE)
                            Main.log.warning("Refusing to extract directory " + name + ": already exists");
                    }
                }
            } else {
                files.add(name);
                for (String dir : DISALLOWED_DIRECTORIES) {
                    if (file.getPath().startsWith(dir)) {
                        if (VERBOSE)
                            Main.log.warning("Refusing to extract " + name + " from " + zip.getName()
                                    + ": parent directory \"" + dir + "\" is not allowed");
                        continue entryLoop;
                    }
                }
                if (DISALLOW_MERGE) {
                    for (String dir : existingDirs) {
                        if (file.getPath().substring(2, file.getPath().length()).replace(File.separator, "/")
                                .startsWith(dir)) {
                            continue entryLoop;
                        }
                    }
                }
                if (!DISALLOW_OVERWRITE || !file.exists()) {
                    file.getParentFile().mkdirs();
                    for (String ext : DISALLOWED_EXTENSIONS) {
                        if (file.getName().endsWith(ext)) {
                            if (VERBOSE)
                                Main.log.warning("Refusing to extract " + name + " from " + zip.getName()
                                        + ": extension \"" + ext + "\" is not allowed");
                            returnValue = false;
                            continue entryLoop;
                        }
                    }
                    BufferedInputStream bIs = new BufferedInputStream(zip.getInputStream(entry));
                    int b;
                    byte[] buffer = new byte[1024];
                    FileOutputStream fOs = new FileOutputStream(file);
                    BufferedOutputStream bOs = new BufferedOutputStream(fOs, 1024);
                    while ((b = bIs.read(buffer, 0, 1024)) != -1)
                        bOs.write(buffer, 0, b);
                    bOs.flush();
                    bOs.close();
                    bIs.close();
                } else {
                    if (VERBOSE)
                        Main.log.warning(
                                "Refusing to extract " + name + " from " + zip.getName() + ": already exists");
                    returnValue = false;
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace(); //TODO
        throw new MPTException(ERROR_COLOR + "Failed to extract archive!");
    }
    return returnValue;
}

From source file:com.jaspersoft.jasperserver.war.OlapGetChart.java

/**
 * Binary streams the specified file to the HTTP response in 1KB chunks
 *
 * @param file The file to be streamed.//from ww  w .  j  av  a2  s. co  m
 * @param response The HTTP response object.
 * @param mimeType The mime type of the file, null allowed.
 *
 * @throws IOException  if there is an I/O problem.
 * @throws FileNotFoundException  if the file is not found.
 */
public static void sendTempFile(File file, HttpServletResponse response, String mimeType)
        throws IOException, FileNotFoundException {

    if (file.exists()) {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

        //  Set HTTP headers
        if (mimeType != null) {
            response.setHeader("Content-Type", mimeType);
        }
        response.setHeader("Content-Length", String.valueOf(file.length()));
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        response.setHeader("Last-Modified", sdf.format(new Date(file.lastModified())));

        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        byte[] input = new byte[1024];
        boolean eof = false;
        while (!eof) {
            int length = bis.read(input);
            if (length == -1) {
                eof = true;
            } else {
                bos.write(input, 0, length);
            }
        }
        bos.flush();
        bis.close();
        bos.close();
    } else {
        throw new FileNotFoundException(file.getAbsolutePath());
    }
    return;
}

From source file:JarMaker.java

/**
 * @param f_name : source zip file path name
 * @param dir_name : target dir file path
 */// w  w w  .  j  a  v  a  2s . com
public static void unpackJar(String f_name, String dir_name) throws IOException {

    BufferedInputStream bism = new BufferedInputStream(new FileInputStream(f_name));

    ZipInputStream zism = new ZipInputStream(bism);

    for (ZipEntry z = zism.getNextEntry(); z != null; z = zism.getNextEntry()) {
        File f = new File(dir_name, z.getName());
        if (z.isDirectory()) {
            f.mkdirs();
        } else {
            f.getParentFile().mkdirs();

            BufferedOutputStream bosm = new BufferedOutputStream(new FileOutputStream(f));
            int i;
            byte[] buffer = new byte[1024 * 512];
            try {
                while ((i = zism.read(buffer, 0, buffer.length)) != -1)
                    bosm.write(buffer, 0, i);
            } catch (IOException ie) {
                throw ie;
            }
            bosm.close();
        }
    }
    zism.close();
    bism.close();
}

From source file:Main.java

public static boolean downloadFile(File file, URL url) throws IOException {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    HttpURLConnection conn = null;
    try {/*from   w ww . jav a2s.  co m*/
        conn = (HttpURLConnection) url.openConnection();
        bis = new BufferedInputStream(conn.getInputStream());
        bos = new BufferedOutputStream(new FileOutputStream(file));

        int contentLength = conn.getContentLength();

        byte[] buffer = new byte[BUFFER_SIZE];
        int read = 0;
        int count = 0;
        while ((read = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, read);
            count += read;
        }
        if (count < contentLength)
            return false;
        int responseCode = conn.getResponseCode();
        if (responseCode / 100 != 2) {
            // error
            return false;
        }
        // finished
        return true;
    } finally {
        try {
            bis.close();
            bos.close();
            conn.disconnect();
        } catch (Exception e) {
        }
    }
}

From source file:com.sec.ose.osi.util.tools.FileOperator.java

public static void copyFile(File pSource, File pDest) throws FileNotFoundException {

    if (pSource == null)
        throw new FileNotFoundException("Source file is not found");

    if (pSource.exists() == false)
        throw new FileNotFoundException(pSource.getPath());

    if (pDest == null)
        throw new FileNotFoundException("Report file is not found");

    BufferedInputStream bi = null;
    BufferedOutputStream bo = null;

    try {/*  w  ww . j a v  a 2 s. c  om*/
        bi = new BufferedInputStream(new FileInputStream(pSource)); // FileNotFoundExeption
        bo = new BufferedOutputStream(new FileOutputStream(pDest));

        byte buffer[] = new byte[BUF_SIZE];

        int readByte = 0;

        while ((readByte = bi.read(buffer)) != -1) { // IOException
            bo.write(buffer, 0, readByte);

        }

    } catch (FileNotFoundException e) {
        log.warn(e);
        throw e;
    } catch (IOException e) {
        log.warn(e);
    } finally {

        if (bo != null) {
            try {
                bo.flush();

            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.warn(e);
            }
            try {
                bo.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.warn(e);
            }

            bo = null;
        }
        if (bi != null) {
            try {
                bi.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                log.warn(e);
            }
            bi = null;
        }
    }

}

From source file:com.elastica.helper.FileUtility.java

public static void extractJar(final String storeLocation, final Class<?> clz) throws IOException {
    File firefoxProfile = new File(storeLocation);
    String location = clz.getProtectionDomain().getCodeSource().getLocation().getFile();

    JarFile jar = new JarFile(location);
    System.out.println("Extracting jar file::: " + location);
    firefoxProfile.mkdir();/*from w ww.j  a  v a 2 s  . c  o m*/

    Enumeration<?> jarFiles = jar.entries();
    while (jarFiles.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) jarFiles.nextElement();
        String currentEntry = entry.getName();
        File destinationFile = new File(storeLocation, currentEntry);
        File destinationParent = destinationFile.getParentFile();

        // create the parent directory structure if required
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(jar.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte[] data = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);

            // read and write till last byte
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                destination.write(data, 0, currentByte);
            }

            destination.flush();
            destination.close();
            is.close();
        }
    }

    FileUtils.deleteDirectory(new File(storeLocation + "\\META-INF"));
    if (OSUtility.isWindows()) {
        new File(storeLocation + "\\" + clz.getCanonicalName().replaceAll("\\.", "\\\\") + ".class").delete();
    } else {
        new File(storeLocation + "/" + clz.getCanonicalName().replaceAll("\\.", "/") + ".class").delete();
    }
}

From source file:Main.java

public static void fastBufferFileCopy(File source, File target) {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    long start = System.currentTimeMillis();
    FileInputStream fis = null;/* w w w .  ja  v a 2 s  .com*/
    FileOutputStream fos = null;
    long size = source.length();
    try {
        fis = new FileInputStream(source);
        bis = new BufferedInputStream(fis);
        fos = new FileOutputStream(target);
        bos = new BufferedOutputStream(fos);

        byte[] barr = new byte[Math.min((int) size, 1 << 20)];
        int read = 0;
        while ((read = bis.read(barr)) != -1) {
            bos.write(barr, 0, read);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        close(fis);
        close(fos);
        close(bis);
        close(bos);
    }
    long end = System.currentTimeMillis();

    String srcPath = source.getAbsolutePath();
    Log.d("Copied " + srcPath + " to " + target,
            ", took " + (end - start) / 1000 + " ms, total size " + nf.format(size) + " Bytes, speed "
                    + ((end - start > 0) ? nf.format(size / (end - start)) : 0) + "KB/s");
}

From source file:net.vexelon.myglob.utils.Utils.java

/**
 * Write input stream data to PRIVATE internal storage file.
 * @param context//from www  . j a v  a  2  s.c o  m
 * @param source
 * @param internalStorageName
 * @throws IOException
 */
public static void writeToInternalStorage(Context context, InputStream source, String internalStorageName)
        throws IOException {

    FileOutputStream fos = null;
    try {
        fos = context.openFileOutput(internalStorageName, Context.MODE_PRIVATE);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        BufferedInputStream bis = new BufferedInputStream(source);
        byte[] buffer = new byte[4096];
        int read = -1;
        while ((read = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, read);
        }
        bos.flush();
        bos.close();
    } catch (FileNotFoundException e) {
        throw new IOException(e.getMessage());
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
        try {
            if (source != null)
                source.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.microsoft.intellij.AzurePlugin.java

private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
    BufferedOutputStream bos = new BufferedOutputStream(new java.io.FileOutputStream(filePath));
    byte[] bytesIn = new byte[1024 * 10];
    int read = 0;
    while ((read = zipIn.read(bytesIn)) != -1) {
        bos.write(bytesIn, 0, read);
    }// w  ww.j  a va  2  s  . co m
    bos.close();
}

From source file:com.blazemeter.bamboo.plugin.ServiceManager.java

public static void unzip(String srcZipFileName, String destDirectoryName, BuildLogger logger) {
    try {//from  w w w  .  j a va  2 s.  c  o m
        BufferedInputStream bufIS = null;
        // create the destination directory structure (if needed)
        File destDirectory = new File(destDirectoryName);
        destDirectory.mkdirs();

        // open archive for reading
        File file = new File(srcZipFileName);
        ZipFile zipFile = new ZipFile(file, ZipFile.OPEN_READ);

        //for every zip archive entry do
        Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            logger.addBuildLogEntry("\tExtracting jtl report: " + entry);

            //create destination file
            File destFile = new File(destDirectory, entry.getName());

            //create parent directories if needed
            File parentDestFile = destFile.getParentFile();
            parentDestFile.mkdirs();

            bufIS = new BufferedInputStream(zipFile.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte data[] = new byte[BUFFER_SIZE];

            // write the current file to disk
            FileOutputStream fOS = new FileOutputStream(destFile);
            BufferedOutputStream bufOS = new BufferedOutputStream(fOS, BUFFER_SIZE);

            while ((currentByte = bufIS.read(data, 0, BUFFER_SIZE)) != -1) {
                bufOS.write(data, 0, currentByte);
            }

            // close BufferedOutputStream
            bufOS.flush();
            bufOS.close();
        }
        bufIS.close();
    } catch (Exception e) {
        logger.addErrorLogEntry("Failed to unzip report: check that it is downloaded");
    }
}