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:io.tempra.AppServer.java

public static void copyJarResourceToFolder(JarURLConnection jarConnection, File destDir) {

    try {//from  w  w w .  j av  a 2  s.c  om
        JarFile jarFile = jarConnection.getJarFile();

        /**
         * Iterate all entries in the jar file.
         */
        for (Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {

            JarEntry jarEntry = e.nextElement();
            String jarEntryName = jarEntry.getName();
            String jarConnectionEntryName = jarConnection.getEntryName();

            /**
             * Extract files only if they match the path.
             */
            if (jarEntryName.startsWith(jarConnectionEntryName)) {

                String filename = jarEntryName.startsWith(jarConnectionEntryName)
                        ? jarEntryName.substring(jarConnectionEntryName.length())
                        : jarEntryName;
                File currentFile = new File(destDir, filename);

                if (jarEntry.isDirectory()) {
                    currentFile.mkdirs();
                } else {
                    InputStream is = jarFile.getInputStream(jarEntry);
                    OutputStream out = FileUtils.openOutputStream(currentFile);
                    IOUtils.copy(is, out);
                    is.close();
                    out.close();
                }
            }
        }
    } catch (IOException e) {
        // TODO add logger
        e.printStackTrace();
    }

}

From source file:FileUtils.java

public static void copyFile(InputStream input, File destination) throws IOException {
    OutputStream output = null;

    output = new FileOutputStream(destination);

    byte[] buffer = new byte[1024];

    int bytesRead = input.read(buffer);

    while (bytesRead >= 0) {
        output.write(buffer, 0, bytesRead);
        bytesRead = input.read(buffer);//from   w  w w.j a v a  2  s  .c  o  m
    }

    input.close();

    output.close();
}

From source file:com.openmeap.file.FileOperationManagerImplTest.java

/**
 * Creates the working/store directories, sets up the logger, and creates the FileOperationManager. 
 * @throws IOException// www  . j av  a  2 s .  c  o  m
 */
@BeforeClass
public static void setUp() throws IOException {
    org.apache.log4j.BasicConfigurator.configure();
    org.apache.log4j.Logger.getLogger("org.apache.commons").setLevel(Level.OFF);
    org.apache.log4j.Logger.getLogger("Locking").setLevel(Level.OFF);
    org.apache.log4j.Logger.getLogger("com.openmeap").setLevel(Level.TRACE);

    new File(STOREDIR).mkdir();
    new File(WORKDIR).mkdir();
    File f = new File(STOREDIR + File.separator + TEST_FILE);
    OutputStream stream = new BufferedOutputStream(new FileOutputStream(f));
    InputStream inputStream = new ByteArrayInputStream(TEST_TEXT.getBytes());
    try {
        Utils.pipeInputStreamIntoOutputStream(inputStream, stream);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }

    mgr = new FileOperationManagerImpl();
    FileResourceManager resMgr = new FileResourceManager(STOREDIR, WORKDIR, false,
            new SLF4JLoggerFacade(LoggerFactory.getLogger("org.apache.commons.transaction.file")));
    mgr.setFileResourceManager(resMgr);
}

From source file:com.photon.phresco.util.FileUtil.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  ww.  j ava2  s  .  com
        }

        //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

            if (!Constants.MACOSX.equals(file)) {
                copyFolder(srcFile, destFile);
            }
        }
    } else {
        //if file, then copy it
        //Use bytes stream to support all file types
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dest);

        byte[] buffer = new byte[BUFFER_SIZE];

        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.dasein.cloud.google.HttpsConnection.java

/** E-mail address of the service account. */

//   public static InputStream getResponseBody(HttpMethod conn) throws Exception {
//      if (conn == null) throw new Exception("Not connected !");
//      return conn.getResponseBodyAsStream();
//   }/*ww  w  .  ja va  2  s . co m*/

public static File writeToFile(InputStream in, String name) throws Exception {

    BufferedReader is = new BufferedReader(new InputStreamReader(in));
    String line = "";
    File f = new File(name);
    OutputStream out = new FileOutputStream(f);
    while ((line = is.readLine()) != null) {
        out.write(line.getBytes());
    }
    out.close();
    in.close();
    return f;
}

From source file:com.buaa.cfs.utils.IOUtils.java

/**
 * Copies from one stream to another.//from www .  j  a v a  2 s . c  om
 *
 * @param in       InputStrem to read from
 * @param out      OutputStream to write to
 * @param buffSize the size of the buffer
 * @param close    whether or not close the InputStream and OutputStream at the end. The streams are closed in the
 *                 finally clause.
 */
public static void copyBytes(InputStream in, OutputStream out, int buffSize, boolean close) throws IOException {
    try {
        copyBytes(in, out, buffSize);
        if (close) {
            out.close();
            out = null;
            in.close();
            in = null;
        }
    } finally {
        if (close) {
            closeStream(out);
            closeStream(in);
        }
    }
}

From source file:com.idocbox.common.file.ZipExtracter.java

/**
 * extract given zip entry file from zip file
 *  to given destrination directory./* w w  w  . jav  a2 s .co  m*/
 * @param zf         ZipFile object.
 * @param zipEntry   zip entry to extract.
 * @param desDir     destrination directory.
 * @param startDirLevel the level to start create directory.
*                      Its value is 1,2,...
 * @throws IOException throw the exception whil desDir is no directory.
 */
private static void extract(final ZipFile zf, final ZipEntry zipEntry, final String desDir,
        final int... startDirLevel) throws IOException {
    //check destination directory.
    File desf = new File(desDir);
    if (!desf.exists()) {
        desf.mkdirs();
    }
    int start = 1;
    if (null != startDirLevel && startDirLevel.length > 0) {
        start = startDirLevel[0];
        if (start < 1) {
            start = 1;
        }
    }

    String startDir = "";
    String zeName = zipEntry.getName();
    String folder = zeName;
    boolean isDir = zipEntry.isDirectory();
    if (null != folder) {
        String[] folders = folder.split("\\/");
        if (null != folders && folders.length > 0) {
            int len = folders.length;
            if (start == 1) {
                startDir = zeName;
            } else {
                if (start > len) {
                    //nothing to extract.
                } else {
                    for (int i = start - 1; i < len; i++) {
                        startDir += "/" + folders[i];
                    }
                    if (null != startDir) {
                        startDir = startDir.substring(1);
                    }
                }
            }
        }
    }
    startDir = StringUtils.trim(startDir);
    if (StringUtils.isNotEmpty(startDir)) {
        StringBuilder desFileName = new StringBuilder(desDir);
        if (!desDir.endsWith("/") && !startDir.startsWith("/")) {
            desFileName.append("/");
        }
        desFileName.append(startDir);

        File destFile = new File(desFileName.toString());
        if (isDir) {//the entry is a dir.
            if (!destFile.exists()) {
                destFile.mkdirs();
            }
        } else {//the entry is a file.
            File parentDir = new File(destFile.getParentFile().getPath());
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            //get entry input stream.
            InputStream is = zf.getInputStream(zipEntry);
            OutputStream os = new FileOutputStream(destFile);
            IOUtils.copy(is, os);
            if (null != is) {
                is.close();
            }
            if (null != os) {
                os.close();
            }
        }
    }

}

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

public static String copyFile(String fileName, String outputFileName) throws IOException {

    File outputFile = new File(outputFileName);
    if (!outputFile.exists())
        outputFile.createNewFile();/*from   w  w  w .j a va  2 s.co  m*/
    System.out.println("Copying " + fileName + " to " + outputFileName);
    OutputStream stream = new FileOutputStream(outputFile);
    InputStream input = FileLocator.openStream(Activator.getDefault().getBundle(), new Path(fileName), false);

    IOUtils.copy(input, stream);
    input.close();
    stream.close();
    return outputFile.getAbsolutePath();
}

From source file:io.undertow.server.handlers.HttpContinueAcceptingHandlerTestCase.java

@BeforeClass
public static void setup() {
    final BlockingHandler blockingHandler = new BlockingHandler();
    final HttpContinueAcceptingHandler handler = new HttpContinueAcceptingHandler(blockingHandler,
            new Predicate() {
                @Override// ww w . j a  v a2 s. co  m
                public boolean resolve(HttpServerExchange value) {
                    return accept;
                }
            });
    DefaultServer.setRootHandler(handler);
    blockingHandler.setRootHandler(new HttpHandler() {
        @Override
        public void handleRequest(final HttpServerExchange exchange) {
            try {
                byte[] buffer = new byte[1024];
                final ByteArrayOutputStream b = new ByteArrayOutputStream();
                int r = 0;
                final OutputStream outputStream = exchange.getOutputStream();
                final InputStream inputStream = exchange.getInputStream();
                while ((r = inputStream.read(buffer)) > 0) {
                    b.write(buffer, 0, r);
                }
                outputStream.write(b.toByteArray());
                outputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:eu.sisob.uma.footils.File.FileFootils.java

public static void copyfile(File f1, File f2) throws FileNotFoundException, IOException {
    InputStream in = new FileInputStream(f1);

    //For Append the file.
    //OutputStream out = new FileOutputStream(f2,true);

    //For Overwrite the file.
    OutputStream out = new FileOutputStream(f2);

    byte[] buf = new byte[1024];
    int len;//from   w w  w  . ja v  a  2  s .  c o  m
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}