Example usage for java.io BufferedOutputStream close

List of usage examples for java.io BufferedOutputStream close

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:JarUtils.java

/** Given a URL check if its a jar url(jar:<url>!/archive) and if it is,
 extract the archive entry into the given dest directory and return a file
 URL to its location. If jarURL is not a jar url then it is simply returned
 as the URL for the jar./* w  ww  .j  av  a 2  s . c  o m*/
        
 @param jarURL the URL to validate and extract the referenced entry if its
   a jar protocol URL
 @param dest the directory into which the nested jar will be extracted.
 @return the file: URL for the jar referenced by the jarURL parameter.
 * @throws IOException 
 */
public static URL extractNestedJar(URL jarURL, File dest) throws IOException {
    // This may not be a jar URL so validate the protocol 
    if (jarURL.getProtocol().equals("jar") == false)
        return jarURL;

    String destPath = dest.getAbsolutePath();
    URLConnection urlConn = jarURL.openConnection();
    JarURLConnection jarConn = (JarURLConnection) urlConn;
    // Extract the archive to dest/jarName-contents/archive
    String parentArchiveName = jarConn.getJarFile().getName();
    // Find the longest common prefix between destPath and parentArchiveName
    int length = Math.min(destPath.length(), parentArchiveName.length());
    int n = 0;
    while (n < length) {
        char a = destPath.charAt(n);
        char b = parentArchiveName.charAt(n);
        if (a != b)
            break;
        n++;
    }
    // Remove any common prefix from parentArchiveName
    parentArchiveName = parentArchiveName.substring(n);

    File archiveDir = new File(dest, parentArchiveName + "-contents");
    if (archiveDir.exists() == false && archiveDir.mkdirs() == false)
        throw new IOException(
                "Failed to create contents directory for archive, path=" + archiveDir.getAbsolutePath());
    String archiveName = jarConn.getEntryName();
    File archiveFile = new File(archiveDir, archiveName);
    File archiveParentDir = archiveFile.getParentFile();
    if (archiveParentDir.exists() == false && archiveParentDir.mkdirs() == false)
        throw new IOException(
                "Failed to create parent directory for archive, path=" + archiveParentDir.getAbsolutePath());
    InputStream archiveIS = jarConn.getInputStream();
    FileOutputStream fos = new FileOutputStream(archiveFile);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    byte[] buffer = new byte[4096];
    int read;
    while ((read = archiveIS.read(buffer)) > 0) {
        bos.write(buffer, 0, read);
    }
    archiveIS.close();
    bos.close();

    // Return the file url to the extracted jar
    return archiveFile.toURL();
}

From source file:org.openmrs.module.report.util.FileUtils.java

public static boolean copyFile(File source, File dest) {
    try {/*  w w  w  .  j  ava2  s .  c  o m*/
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
        byte[] data = new byte[2 * 1024];
        int count;
        while ((count = in.read(data, 0, data.length)) != -1) {
            out.write(data, 0, count);
        }
        out.flush();
        out.close();
        in.close();
        return true;
    } catch (FileNotFoundException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}

From source file:ebay.dts.client.FileTransferActions.java

private static String compressFileToGzip(String inFilename) throws EbayConnectorException {

    // compress the xml file into gz file in the save folder
    String outFilename = null;//from w w w . j a v  a  2s.c  om
    String usingPath = inFilename.substring(0, inFilename.lastIndexOf(File.separator) + 1);
    String fileName = inFilename.substring(inFilename.lastIndexOf(File.separator) + 1);
    outFilename = usingPath + fileName + ".gz";

    try {

        BufferedReader in = new BufferedReader(new FileReader(inFilename));
        BufferedOutputStream out = new BufferedOutputStream(
                new GZIPOutputStream(new FileOutputStream(outFilename)));
        logger.trace("Writing gz file to: " + Utility.getFileLabel(outFilename));

        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();
        out.close();

    } catch (FileNotFoundException e) {
        logger.error("Cannot gzip file: " + inFilename);
        throw new EbayConnectorException("Cannot gzip file: " + inFilename, e);
    } catch (IOException e) {
        logger.error("Cannot gzip file: " + inFilename);
        throw new EbayConnectorException("Cannot gzip file: " + inFilename, e);
    }

    logger.info("The compressed file has been saved to " + outFilename);
    return outFilename;
}

From source file:com.dc.util.file.FileSupport.java

public static void writeBinaryFile(File inputFile, File outputFile) throws IOException {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {// ww  w.j a  va 2  s.c o  m
        bis = new BufferedInputStream(new FileInputStream(inputFile));
        bos = new BufferedOutputStream(new FileOutputStream(outputFile));
        copyStream(bis, bos);
    } finally {
        if (bis != null) {
            bis.close();
        }
        if (bos != null) {
            bos.close();
        }
    }

}

From source file:Main.java

public static void copyFile(File sourceFile, File targetFile) throws IOException {
    BufferedInputStream inBuff = null;
    BufferedOutputStream outBuff = null;
    try {//from   ww  w .  j  a  va  2s .  co m
        inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
        outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
        byte[] buffer = new byte[BUFFER];
        int length;
        while ((length = inBuff.read(buffer)) != -1) {
            outBuff.write(buffer, 0, length);
        }
        outBuff.flush();
    } finally {
        if (inBuff != null) {
            inBuff.close();
        }
        if (outBuff != null) {
            outBuff.close();
        }
    }
}

From source file:com.seleniumtests.util.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();

    try (JarFile jar = new JarFile(location);) {
        logger.info("Extracting jar file::: " + location);
        firefoxProfile.mkdir();//  w ww. ja va 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
                try (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 boolean OutPutImage(File file, Bitmap bitmap) {
    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();/*w w  w  .j  a  v a  2 s .c o  m*/
    }
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        if (bos != null) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            bos.flush();
            fos.flush();
            return true;
        } else {
            return false;
        }
    } catch (IOException e) {
        return false;
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:oneDrive.OneDriveAPI.java

public static void uploadFile(String filePath) {
    URLConnection urlconnection = null;
    try {//from   w  ww .j a  va 2  s  .  co m
        File file = new File(UPLOAD_PATH + filePath);
        URL url = new URL(DRIVE_PATH + file.getName() + ":/content");
        urlconnection = url.openConnection();
        urlconnection.setDoOutput(true);
        urlconnection.setDoInput(true);

        if (urlconnection instanceof HttpURLConnection) {
            try {
                ((HttpURLConnection) urlconnection).setRequestMethod("PUT");
                ((HttpURLConnection) urlconnection).setRequestProperty("Content-type",
                        "application/octet-stream");
                ((HttpURLConnection) urlconnection).addRequestProperty("Authorization",
                        "Bearer " + ACCESS_TOKEN);
                ((HttpURLConnection) urlconnection).connect();

            } catch (ProtocolException e) {
                e.printStackTrace();
            }
        }

        BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        int i;
        // read byte by byte until end of stream
        while ((i = bis.read()) >= 0) {
            bos.write(i);
        }
        bos.flush();
        bos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:de.nrw.hbz.deepzoomer.fileUtil.FileUtil.java

/**
 * <p><em>Title: Create a File from a Base64 encoded String</em></p>
 * <p>Description: Method creates a file from the bytestream 
 * representing the original PDF, that should be converted</p>
 * //from  www.j  ava 2  s .  co m
 * @param stream <code>String</code> 
 * @return <code>String</code> Filename of newly created temporary File
 */
public static String saveBase64ByteStringToFile(File outputFile, String stream) {
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    try {
        fos = new FileOutputStream(outputFile);
        bos = new BufferedOutputStream(fos);
        bos.write(Base64.decodeBase64(stream.getBytes("UTF-8")));
        bos.flush();
        bos.close();

    } catch (IOException ioExc) {
        log.error(ioExc);
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
    }
    return outputFile.getName();
}

From source file:net.sf.jasperreports.engine.xml.JRXmlTemplateWriter.java

/**
 * Writes the XML representation of a template to a file.
 * /* ww w . ja  v a  2 s .co  m*/
 * @param jasperReportsContext
 * @param template the template
 * @param outputFile the output file name
 * @param encoding the XML encoding to use
 */
public static void writeTemplateToFile(JasperReportsContext jasperReportsContext, JRTemplate template,
        String outputFile, String encoding) {
    BufferedOutputStream fileOut = null;
    boolean close = true;
    try {
        fileOut = new BufferedOutputStream(new FileOutputStream(outputFile));
        writeTemplate(jasperReportsContext, template, fileOut, encoding);

        fileOut.flush();
        close = false;
        fileOut.close();
    } catch (FileNotFoundException e) {
        throw new JRRuntimeException(e);
    } catch (IOException e) {
        throw new JRRuntimeException(e);
    } finally {
        if (fileOut != null && close) {
            try {
                fileOut.close();
            } catch (IOException e) {
                log.warn("Could not close file " + outputFile, e);
            }
        }
    }
}