Example usage for java.io OutputStream close

List of usage examples for java.io OutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

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

Usage

From source file:net.lightbody.bmp.proxy.jetty.util.IO.java

/**
 * closes an output stream, and logs exceptions
 *
 * @param os the output stream to close//  w  w w  .  j  ava2 s  . c om
 */
public static void close(OutputStream os) {
    try {
        if (os != null)
            os.close();
    } catch (IOException e) {
        LogSupport.ignore(log, e);
    }
}

From source file:Main.java

/** Copy binary file */
public static boolean copyFile(File srcFile, File dstFile) {
    try {//from  w w w.  j  a v a 2 s.c  om
        InputStream in = new FileInputStream(srcFile);
        if (dstFile.exists()) {
            dstFile.delete();
        }

        OutputStream out = new FileOutputStream(dstFile);
        try {
            int cnt;
            byte[] buf = new byte[4096];
            while ((cnt = in.read(buf)) >= 0) {
                out.write(buf, 0, cnt);
            }
        } finally {
            out.close();
            in.close();
        }
        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:edu.isi.karma.util.FileUtil.java

public static void copyFiles(File destination, File source) throws FileNotFoundException, IOException {
    if (!destination.exists()) {
        destination.createNewFile();/*from  w w  w  .j  a va  2 s  . c  om*/
    }
    InputStream in = new FileInputStream(source);
    OutputStream out = new FileOutputStream(destination);

    byte[] buf = new byte[1024];
    int len;

    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
    logger.debug("Done copying contents of " + source.getName() + " to " + destination.getName());
}

From source file:fiftyone.mobile.detection.webapp.ImageCache.java

/**
 * Adds the image at the width and height provided to the cache.
 * @param imageLocal/*from www.  j  av a  2  s .  c om*/
 * @param width
 * @param height
 * @param imageAsStream
 * @throws IOException 
 */
synchronized static void add(File physicalPath, File cacheFile, int width, int height,
        InputStream imageAsStream) throws IOException {
    new File(cacheFile.getParent()).mkdirs();
    cacheFile.createNewFile();
    OutputStream outputStream = new FileOutputStream(cacheFile);

    int read = 0;
    byte[] bytes = new byte[1024 ^ 2];

    while ((read = imageAsStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }

    outputStream.close();
}

From source file:gov.nasa.ensemble.dictionary.nddl.NDDLUtil.java

public static void copyDirectory(File sourceLocation, File targetLocation) throws IOException {
    if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists()) {
            targetLocation.mkdir();/*w  w w  .  j  ava  2  s  .c o m*/
        }

        String[] children = sourceLocation.list();
        for (int i = 0; i < children.length; i++) {
            copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
        }
    } else {

        InputStream in = new FileInputStream(sourceLocation);
        OutputStream out = new FileOutputStream(targetLocation);
        IOUtils.copy(in, out);
        in.close();
        out.close();
    }
}

From source file:de.sandmage.opportunisticmail.crypto.OpenPGP.java

static byte[] compressFile(byte[] data, int algorithm) throws IOException {
    byte[] buffer = new byte[4096];
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(algorithm);
    PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
    OutputStream pOut = lData.open(comData.open(bOut), PGPLiteralData.BINARY, "fancyfile", new Date(), buffer);

    //        PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY,
    //            data);
    pOut.write(data);//from   www. j a v a 2s  .  co m
    pOut.close();
    comData.close();
    return bOut.toByteArray();
}

From source file:com.fluidops.iwb.cms.util.IWBCmsUtil.java

public static File upload(String filename, Resource subject, InputStream is, Collector collector)
        throws FileNotFoundException, IOException {
    if (Config.getConfig().uploadFileClass().equals(LocalFile.class.getName()))
        GenUtil.mkdirs(IWBFileUtil.getUploadFolder());

    File file = uploadedFileFor(filename);
    if (file.exists())
        throw new IllegalStateException("Error during upload: File " + filename + " already exists.");

    ReadWriteDataManager dm = null;/*from  ww  w .  j a  va 2  s.c o  m*/
    try {
        dm = ReadWriteDataManagerImpl.openDataManager(Global.repository);

        OutputStream out = file.getOutputStream();
        out.write(GenUtil.readUrlToBuffer(is).toByteArray());
        out.flush();
        out.close();

        // if we have a page subject, write triple (subject, hasFile, file)
        ValueFactory vf = ValueFactoryImpl.getInstance();
        Context c = Context.getFreshUserContextWithURI(getFileContextURI(file), ContextLabel.FILE_UPLOAD);
        c.setEditable(false);

        if (subject != null)
            dm.addToContext(vf.createStatement(subject, Vocabulary.SYSTEM.ATTACHEDFILE, file.getURI()), c);

        dm.addToContext(collector.collectRDF(file, file.getURI()), c);

        return file;
    } finally {
        ReadWriteDataManagerImpl.closeQuietly(dm);
    }
}

From source file:Main.java

static File makeTempJar(File moduleFile) throws IOException {
    String prefix = moduleFile.getName();
    if (prefix.endsWith(".jar") || prefix.endsWith(".JAR")) { // NOI18N
        prefix = prefix.substring(0, prefix.length() - 4);
    }/* w w w.  ja  va  2 s . co m*/
    if (prefix.length() < 3)
        prefix += '.';
    if (prefix.length() < 3)
        prefix += '.';
    if (prefix.length() < 3)
        prefix += '.';
    String suffix = "-test.jar"; // NOI18N
    File physicalModuleFile = File.createTempFile(prefix, suffix);
    physicalModuleFile.deleteOnExit();
    InputStream is = new FileInputStream(moduleFile);
    try {
        OutputStream os = new FileOutputStream(physicalModuleFile);
        try {
            byte[] buf = new byte[4096];
            int i;
            while ((i = is.read(buf)) != -1) {
                os.write(buf, 0, i);
            }
        } finally {
            os.close();
        }
    } finally {
        is.close();
    }
    return physicalModuleFile;
}

From source file:Main.java

public static void copyFolder(File src, File dest) throws IOException {

    if (src.isDirectory()) {

        //if directory not exists, create it
        if (!dest.exists()) {
            dest.mkdir();/*from w  w w.ja  va  2s. c o m*/
        }

        //list all the directory contents
        String files[] = src.list();

        for (String file : files) {
            //construct the src and dest file structure
            File srcFile = new File(src, file);
            File destFile = new File(dest, file);
            //recursive copy
            copyFolder(srcFile, destFile);
        }

    } else {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dest);

        byte[] buffer = new byte[1024];

        int length;
        //copy the file content in bytes
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }

        in.close();
        out.close();
    }
}

From source file:org.shareok.data.webserv.WebUtil.java

public static void setupFileDownload(HttpServletResponse response, String downloadPath) {
    try {//from  w w w . j a  va 2  s. c o  m
        File file = new File(downloadPath);
        if (!file.exists()) {
            String errorMessage = "Sorry. The file you are looking for does not exist";
            System.out.println(errorMessage);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
            outputStream.close();
            return;
        }

        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            System.out.println("mimetype is not detectable, will take default");
            mimeType = "application/octet-stream";
        }

        response.setContentType(mimeType);
        /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser 
        while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/
        response.setHeader("Content-Disposition",
                String.format("attachment; filename=\"" + file.getName() + "\""));

        /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/
        //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));

        response.setContentLength((int) file.length());

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

        //Copy bytes from source to destination(outputstream in this example), closes both streams.
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } catch (IOException ioex) {
        logger.error("Cannot set up a file download.", ioex);
    }
}