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:brainleg.app.util.AppWeb.java

/**
 * Copied from ITNProxy//ww  w.  j  av  a2  s  . co  m
 */
private static HttpURLConnection doPost(String url, byte[] bytes) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) HttpConfigurable.getInstance().openConnection(url);

    connection.setReadTimeout(60 * 1000);
    connection.setConnectTimeout(10 * 1000);
    connection.setRequestMethod(HTTP_POST);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestProperty(HTTP_CONTENT_TYPE, String.format("%s; charset=%s", HTTP_WWW_FORM, ENCODING));
    connection.setRequestProperty(HTTP_CONTENT_LENGTH, Integer.toString(bytes.length));

    OutputStream out = new BufferedOutputStream(connection.getOutputStream());
    try {
        out.write(bytes);
        out.flush();
    } finally {
        out.close();
    }

    return connection;
}

From source file:com.photon.phresco.util.FileUtil.java

public static File writeFileFromInputStream(InputStream inputStream, String tempZip) throws PhrescoException {
    File tempZipFile = new File(tempZip);
    try {/*from  w  w  w .j av  a2  s  .c  o m*/
        if (!tempZipFile.exists()) {
            tempZipFile.createNewFile();
        }
        OutputStream out = new FileOutputStream(new File(tempZip));
        int read = 0;
        byte[] bytes = new byte[BUFFER_SIZE];
        while ((read = inputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        inputStream.close();
        out.flush();
        out.close();
    } catch (Exception e) {
        throw new PhrescoException(e);
    }

    return tempZipFile;
}

From source file:Main.java

public static boolean cutPasteFile(File inputFile, File outputFile, int currentCount) {

    // ######################## ALPHA RELEASE 1.1.2 ########################

    /* ALPHA RELEASE 1.1.2 BUG FIX
     * // w  w  w.j a v  a 2  s .  c o m
     * BUG DESCRIPTION:
     * 
     * This patch fixes the bug  that is encountered when a file has been 
     * detected to be designated and its file name already exists in the 
     * designation folder, the File Designation Scan overwrites the file 
     * inside the designation folder, creating a bug which deletes the file,
     * losing the said file permanently.
     * 
     * GITHUB Issue Link:  https://github.com/idclxvii/SharpFixAndroid/issues/1
     * 
     * Solution:
     * 
     *       Renames the file name and checks if the renamed file already exists.
     *       If it does, call this method recursively until there's no occurrences 
     *       of the current file name chosen. If the file doesn't exist yet, then 
     *       proceed the cut and paste procedures
     * 
     * */

    if (outputFile.exists()) {
        File renamedFile = new File("");
        if (currentCount > 0) {
            // this is the 2nd time occurrence, in short Test (x).jpg, where x is any integer greater than 1

            currentCount++;
            renamedFile = new File(outputFile.getParent(),
                    outputFile.getName().substring(0, outputFile.getName().lastIndexOf("(")) // "test (0).jpg" returns "test ("
                            + " (" + currentCount + ")"
                            + outputFile.getName().substring(outputFile.getName().lastIndexOf(".")) // test.xml returns .xml
            );

        } else {
            // Test case: File.txt -> File (1).txt
            currentCount++;
            renamedFile = new File(outputFile.getParent(),
                    outputFile.getName().substring(0, outputFile.getName().lastIndexOf(".")) // test.xml returns test
                            + " (" + currentCount + ")"
                            + outputFile.getName().substring(outputFile.getName().lastIndexOf(".")) // test.xml returns .xml
            );
        }
        // rename output file

        return cutPasteFile(inputFile, renamedFile, currentCount);
        // recursively call 
    } else {
        try {
            InputStream is = new FileInputStream(inputFile);
            OutputStream os = new FileOutputStream(outputFile);
            byte[] buffer = new byte[1024];
            int length;
            //copy the file content in bytes 
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            is.close();
            os.close();
            //delete the original file
            inputFile.delete();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

}

From source file:Main.java

public static int upZipFile(File zipFile, String folderPath) throws IOException {
    ZipFile zfile = new ZipFile(zipFile);
    Enumeration zList = zfile.entries();
    ZipEntry ze = null;//from   w ww .ja  va 2s.co m
    byte[] buf = new byte[1024];
    while (zList.hasMoreElements()) {
        ze = (ZipEntry) zList.nextElement();
        if (ze.isDirectory()) {
            String dirstr = folderPath + ze.getName();
            dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
            File f = new File(dirstr);
            f.mkdirs();
            continue;
        }
        OutputStream os = new BufferedOutputStream(
                new FileOutputStream(getRealFileName(folderPath, ze.getName())));
        InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
        int readLen = 0;
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            os.write(buf, 0, readLen);
        }
        is.close();
        os.close();
    }
    zfile.close();
    return 0;
}

From source file:Main.java

public static boolean prepareDex(Context context, File dexInternalStoragePath, String dexFile) {
    BufferedInputStream bis = null;
    OutputStream dexWriter = null;

    try {// w ww . j a va2  s . co  m
        bis = new BufferedInputStream(context.getAssets().open(dexFile));
        dexWriter = new BufferedOutputStream(new FileOutputStream(dexInternalStoragePath));
        byte[] buf = new byte[BUF_SIZE];
        int len;
        while ((len = bis.read(buf, 0, BUF_SIZE)) > 0) {
            dexWriter.write(buf, 0, len);
        }
        dexWriter.close();
        bis.close();
        return true;
    } catch (IOException e) {
        if (dexWriter != null) {
            try {
                dexWriter.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        return false;
    }
}

From source file:org.elasticsearch.discovery.ec2.Ec2DiscoveryClusterFormationTests.java

/**
 * Creates mock EC2 endpoint providing the list of started nodes to the DescribeInstances API call
 *//*from  ww  w . java2s. c o  m*/
@BeforeClass
public static void startHttpd() throws Exception {
    logDir = createTempDir();
    httpServer = MockHttpServer
            .createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress().getHostAddress(), 0), 0);

    httpServer.createContext("/", (s) -> {
        Headers headers = s.getResponseHeaders();
        headers.add("Content-Type", "text/xml; charset=UTF-8");
        String action = null;
        for (NameValuePair parse : URLEncodedUtils.parse(IOUtils.toString(s.getRequestBody()),
                StandardCharsets.UTF_8)) {
            if ("Action".equals(parse.getName())) {
                action = parse.getValue();
                break;
            }
        }
        assertThat(action, equalTo("DescribeInstances"));

        XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
        xmlOutputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);
        StringWriter out = new StringWriter();
        XMLStreamWriter sw;
        try {
            sw = xmlOutputFactory.createXMLStreamWriter(out);
            sw.writeStartDocument();

            String namespace = "http://ec2.amazonaws.com/doc/2013-02-01/";
            sw.setDefaultNamespace(namespace);
            sw.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, "DescribeInstancesResponse", namespace);
            {
                sw.writeStartElement("requestId");
                sw.writeCharacters(UUID.randomUUID().toString());
                sw.writeEndElement();

                sw.writeStartElement("reservationSet");
                {
                    Path[] files = FileSystemUtils.files(logDir);
                    for (int i = 0; i < files.length; i++) {
                        Path resolve = files[i].resolve("transport.ports");
                        if (Files.exists(resolve)) {
                            List<String> addresses = Files.readAllLines(resolve);
                            Collections.shuffle(addresses, random());

                            sw.writeStartElement("item");
                            {
                                sw.writeStartElement("reservationId");
                                sw.writeCharacters(UUID.randomUUID().toString());
                                sw.writeEndElement();

                                sw.writeStartElement("instancesSet");
                                {
                                    sw.writeStartElement("item");
                                    {
                                        sw.writeStartElement("instanceId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("imageId");
                                        sw.writeCharacters(UUID.randomUUID().toString());
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceState");
                                        {
                                            sw.writeStartElement("code");
                                            sw.writeCharacters("16");
                                            sw.writeEndElement();

                                            sw.writeStartElement("name");
                                            sw.writeCharacters("running");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateDnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("dnsName");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("instanceType");
                                        sw.writeCharacters("m1.medium");
                                        sw.writeEndElement();

                                        sw.writeStartElement("placement");
                                        {
                                            sw.writeStartElement("availabilityZone");
                                            sw.writeCharacters("use-east-1e");
                                            sw.writeEndElement();

                                            sw.writeEmptyElement("groupName");

                                            sw.writeStartElement("tenancy");
                                            sw.writeCharacters("default");
                                            sw.writeEndElement();
                                        }
                                        sw.writeEndElement();

                                        sw.writeStartElement("privateIpAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();

                                        sw.writeStartElement("ipAddress");
                                        sw.writeCharacters(addresses.get(0));
                                        sw.writeEndElement();
                                    }
                                    sw.writeEndElement();
                                }
                                sw.writeEndElement();
                            }
                            sw.writeEndElement();
                        }
                    }
                }
                sw.writeEndElement();
            }
            sw.writeEndElement();

            sw.writeEndDocument();
            sw.flush();

            final byte[] responseAsBytes = out.toString().getBytes(StandardCharsets.UTF_8);
            s.sendResponseHeaders(200, responseAsBytes.length);
            OutputStream responseBody = s.getResponseBody();
            responseBody.write(responseAsBytes);
            responseBody.close();
        } catch (XMLStreamException e) {
            Loggers.getLogger(Ec2DiscoveryClusterFormationTests.class).error("Failed serializing XML", e);
            throw new RuntimeException(e);
        }
    });

    httpServer.start();
}

From source file:org.cloudfoundry.caldecott.client.TunnelHelper.java

private static File copyCaldecottZipFile(ClassPathResource cpr) throws IOException {
    File temp = File.createTempFile("caldecott", "zip");
    InputStream in = cpr.getInputStream();
    OutputStream out = new FileOutputStream(temp);
    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = in.read(bytes)) != -1) {
        out.write(bytes, 0, read);/*from w w  w . ja  v  a2  s  . com*/
    }
    in.close();
    out.flush();
    out.close();
    return temp;
}

From source file:com.buglabs.dragonfly.util.WSHelper.java

/**
 * @param url//from   w  w w .  j  a v  a 2  s  .  c o  m
 * @param inputStream
 * @return
 * @throws IOException
 */
protected static String post(URL url, InputStream inputStream) throws IOException {
    URLConnection connection = url.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);

    OutputStream stream = connection.getOutputStream();
    writeTo(stream, inputStream);
    stream.flush();
    stream.close();

    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    String line, resp = new String("");
    while ((line = rd.readLine()) != null) {
        resp = resp + line + "\n";
    }
    rd.close();
    is.close();

    return resp;
}

From source file:jfix.zk.Medias.java

public static File asFile(Media media) {
    try {/*from  ww  w  . j  ava2 s.  co  m*/
        File directory = Files.createTempDirectory("jfix-media").toFile();
        directory.deleteOnExit();
        File file = new File(directory.getPath() + File.separator + media.getName());
        OutputStream output = new FileOutputStream(file);
        if (media.isBinary()) {
            InputStream input = Medias.asStream(media);
            IOUtils.copy(input, output);
            input.close();
        } else {
            Reader input = Medias.asReader(media);
            IOUtils.copy(input, output);
            input.close();
        }
        output.close();
        return file;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.thalesgroup.hudson.plugins.copyarchiver.FilePathArchiver.java

/**
 * Reads from a tar stream and stores obtained files to the base dir.
 * @param isFlatten true if flatten//  w w w  .  j  a va 2s  .c  o  m
 * @param name the name
 * @param baseDir the base directory
 * @param in the inputstream
 * @throws IOException the IOException
 */
@SuppressWarnings("unchecked")
private static void readFromTar(boolean isFlatten, String name, File baseDir, InputStream in)
        throws IOException {
    TarInputStream t = new TarInputStream(in);
    try {
        TarEntry te;
        while ((te = t.getNextEntry()) != null) {

            File f = new File(baseDir, te.getName());
            if (te.isDirectory()) {
                if (!isFlatten)
                    f.mkdirs();
            } else {
                if (!isFlatten) {
                    File parent = f.getParentFile();
                    if (parent != null)
                        parent.mkdirs();
                } else {
                    f = new File(baseDir, getFileNameWithoutLeadingDirectory(te.getName()));
                }

                OutputStream fos = new FileOutputStream(f);
                try {
                    IOUtils.copy(t, fos);
                } finally {
                    fos.close();
                }
                f.setLastModified(te.getModTime().getTime());
                int mode = te.getMode() & 0777;
                if (mode != 0 && !Functions.isWindows()) // be defensive
                    try {
                        LIBC.chmod(f.getPath(), mode);
                    } catch (NoClassDefFoundError e) {
                        // be defensive. see http://www.nabble.com/-3.0.6--Site-copy-problem%3A-hudson.util.IOException2%3A--java.lang.NoClassDefFoundError%3A-Could-not-initialize-class--hudson.util.jna.GNUCLibrary-td23588879.html
                    }
            }

        }
    } catch (IOException e) {
        throw new IOException2("Failed to extract " + name, e);
    } finally {
        t.close();
    }
}