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:org.shareok.data.webserv.WebUtil.java

public static void downloadFileFromServer(HttpServletResponse response, String downloadPath) {

    try {//w  w  w  .  ja  v a 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 download file responding to downloading resquest!", ioex);
    }
}

From source file:no.ntnu.wifimanager.ServerUtilities.java

/**
 * Issue a POST request to server.//  www. j a va 2 s  .com
 *
 * @param serverUrl POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
public static void HTTPpost(String serverUrl, Map<String, String> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(serverUrl);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + serverUrl);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    Log.v(LOG_TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", contentType);
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();

        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:fitnesse.http.ResponseParser.java

public static ResponseParser performHttpRequest(String hostname, int hostPort, RequestBuilder builder)
        throws IOException {
    Socket socket = new Socket(hostname, hostPort);
    OutputStream socketOut = socket.getOutputStream();
    InputStream socketIn = socket.getInputStream();
    builder.send(socketOut);/*  w ww.  j a  va 2s  .  c  om*/
    socketOut.flush();
    try {
        return new ResponseParser(socketIn);
    } finally {
        socketOut.close();
        socket.close();
    }
}

From source file:Main.java

private static void writeNonEmptyFile(final File file) {
    try {/* ww  w . ja  v  a2 s  .  c  o  m*/
        final OutputStream outputStream = new DataOutputStream(new FileOutputStream(file));
        final int expectedLength = 10;
        outputStream.write(expectedLength);
        // The negative beginning index is to accommodate the header. Fancy. Ever so fancy.
        for (int i = -3; i < expectedLength; i++)
            outputStream.write(0x0);
        outputStream.close();
    } catch (final IOException e) {
        throw new RuntimeException("Exception trying to create non-empty file!", e);
    }
}

From source file:Main.java

public static void upZipFile(File zipFile, String folderPath) {
    ZipFile zf;//from w  ww.  j a v  a2 s .c  o  m
    try {
        zf = new ZipFile(zipFile);
        for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
            ZipEntry entry = ((ZipEntry) entries.nextElement());
            if (entry.isDirectory()) {
                String dirstr = entry.getName();
                dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
                File f = new File(dirstr);
                f.mkdir();
                continue;
            }

            InputStream in = zf.getInputStream(entry);
            String str = folderPath + File.separator + entry.getName();
            str = new String(str.getBytes("8859_1"), "GB2312");
            File desFile = new File(str);
            if (!desFile.exists()) {
                File fileParentDir = desFile.getParentFile();
                if (!fileParentDir.exists()) {
                    fileParentDir.mkdirs();
                }
                desFile.createNewFile();
            }

            OutputStream out = new FileOutputStream(desFile);
            byte buffer[] = new byte[BUFF_SIZE];
            int realLength;
            while ((realLength = in.read(buffer)) > 0) {
                out.write(buffer, 0, realLength);
            }
            in.close();
            out.close();
        }
    } catch (ZipException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.android.dumprendertree2.FsUtils.java

public static void closeOutputStream(OutputStream outputStream) {
    try {//from w  w  w  .  j a  v  a 2s . co  m
        if (outputStream != null) {
            outputStream.close();
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Couldn't close stream!", e);
    }
}

From source file:com.idsmanager.eagleeye.net.SimpleMultipartEntity.java

/**
 * A utility function to close an output stream without raising an
 * exception.//from  w  ww.j ava 2 s . com
 *
 * @param os
 *            output stream to close safely
 */
public static void silentCloseOutputStream(OutputStream os) {
    try {
        if (os != null) {
            os.close();
        }
    } catch (IOException e) {
    }
}

From source file:com.aqnote.shared.cryptology.util.lang.StreamUtil.java

public static void close(OutputStream os) {
    try {// w  ww  . j ava2 s  .  c om
        if (os != null)
            os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ca.simplegames.micro.utils.IO.java

/**
 * Close the given stream if the stream is not null.
 *
 * @param s The stream// w  ww .j  a va  2  s .com
 */

public static void close(OutputStream s) {
    if (s != null) {
        try {
            s.close();
        } catch (Exception e) {
            log.error("Error closing stream: " + e.getMessage());
        }
    }
}

From source file:ca.weblite.codename1.netbeans.Installer.java

private static void storeEditableProperties(final Project prj, final String propertiesPath,
        final EditableProperties ep) throws IOException {
    try {/*  w w  w.j  av  a  2 s  .  co  m*/
        ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction<Void>() {
            @Override
            public Void run() throws IOException {
                FileObject propertiesFo = prj.getProjectDirectory().getFileObject(propertiesPath);
                if (propertiesFo != null) {
                    OutputStream os = null;
                    try {
                        os = propertiesFo.getOutputStream();
                        ep.store(os);
                    } finally {
                        if (os != null) {
                            os.close();
                        }
                    }
                }
                return null;
            }
        });
    } catch (MutexException ex) {
    }
}