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:com.ibm.bi.dml.runtime.io.IOUtilFunctions.java

/**
 * //  w ww .j  av  a2  s. c o  m
 * @param is
 */
public static void closeSilently(OutputStream os) {
    try {
        if (os != null)
            os.close();
    } catch (Exception ex) {
        LOG.error("Failed to close output stream.", ex);
    }
}

From source file:Main.java

/**
 * Issue a POST request to the server.//from w  w  w .j  a  v  a2  s  . c  o m
 *
 * @param endpoint POST address.
 * @param params request parameters.
 * @return response
 * @throws IOException propagated from POST.
 */
private static String executePost(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    StringBuffer response = new StringBuffer();
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    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(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

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

        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response.toString();
}

From source file:Main.java

public static String savetoJPEG(byte[] data, int width, int height, String file) {
    Rect frame = new Rect(0, 0, width, height);
    YuvImage img = new YuvImage(data, ImageFormat.NV21, width, height, null);
    OutputStream os = null;
    File jpgfile = new File(file);
    try {/*  w  ww .  ja  v  a2 s  .  co m*/
        os = new FileOutputStream(jpgfile);
        img.compressToJpeg(frame, 100, os);
        os.flush();
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return jpgfile.getPath();
}

From source file:Main.java

public static void saveBitmapToSDCard(Bitmap bitmap, String path) {
    OutputStream outputStream = null;
    try {/*from  www .java2 s  .  c o m*/
        outputStream = new FileOutputStream(path);
        if (outputStream != null) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
            outputStream.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void writeExtractedFileToDisk(InputStream in, OutputStream outs) throws IOException {
    byte[] buffer = new byte[1024];
    int length;/*from   w w  w  .j  av a 2 s  .  co  m*/
    while ((length = in.read(buffer)) > 0) {
        outs.write(buffer, 0, length);
    }
    outs.flush();
    outs.close();
    in.close();
}

From source file:org.envirocar.app.network.HTTPClient.java

public static HttpEntity createEntity(byte[] data) throws IOException {
    AbstractHttpEntity entity;/*from w  ww  . ja va  2 s .co m*/
    if (data.length < MIN_GZIP_SIZE) {
        entity = new ByteArrayEntity(data);
    } else {
        ByteArrayOutputStream arr = new ByteArrayOutputStream();
        OutputStream zipper = new GZIPOutputStream(arr);
        zipper.write(data);
        zipper.close();
        entity = new ByteArrayEntity(arr.toByteArray());
        entity.setContentEncoding("gzip");
    }
    return entity;
}

From source file:edu.harvard.med.screensaver.ui.arch.util.JSFUtils.java

/**
 * Performs the necessary steps to return server-side data, provided as an
 * InputStream, to an HTTP client. Must be called within a JSF-enabled servlet
 * environment.// w  w w .ja va2s . co m
 *
 * @param facesContext the JSF FacesContext
 * @param dataInputStream an InputStream containing the data to send to the HTTP client
 * @param contentLocation set the "content-location" HTTP header to this value, allowing the downloaded file to be named
 * @param mimeType the MIME type of the file being sent
 * @throws IOException
 */
public static void handleUserDownloadRequest(FacesContext facesContext, InputStream dataInputStream,
        String contentLocation, String mimeType) throws IOException {
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    if (mimeType == null && contentLocation != null) {
        mimeType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(contentLocation);
    }
    if (mimeType != null) {
        response.setContentType(mimeType);
    }

    // NOTE: the second line does the trick with the filename. leaving first line in for posterity
    response.setHeader("Content-Location", contentLocation);
    response.setHeader("Content-disposition", "attachment; filename=\"" + contentLocation + "\"");

    OutputStream out = response.getOutputStream();
    IOUtils.copy(dataInputStream, out);
    out.close();

    // skip Render-Response JSF lifecycle phase, since we're generating a
    // non-Faces response
    facesContext.responseComplete();
}

From source file:Main.java

public static void streamCopy(final InputStream bodyIs, final OutputStream out) throws IOException {
    byte[] buffer = new byte[2048];
    int read;//from www.  j av  a  2 s .  c o  m
    while ((read = bodyIs.read(buffer)) > 0) {
        out.write(buffer, 0, read);
    }
    bodyIs.close();
    out.close();
}

From source file:Main.java

static byte[] httpRequest(String url, byte[] requestBytes, int connectionTimeOutMs, int readTimeOutMs) {
    byte[] bArr = null;
    if (!(url == null || requestBytes == null)) {
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;
        try {/*from  w w w  .  j a v  a 2 s . co  m*/
            urlConnection = (HttpURLConnection) new URL(url).openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setConnectTimeout(connectionTimeOutMs);
            urlConnection.setReadTimeout(readTimeOutMs);
            urlConnection.setFixedLengthStreamingMode(requestBytes.length);
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(requestBytes);
            outputStream.close();
            if (urlConnection.getResponseCode() != 200) {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            } else {
                inputStream = urlConnection.getInputStream();
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[16384];
                while (true) {
                    int chunkSize = inputStream.read(buffer);
                    if (chunkSize < 0) {
                        break;
                    } else if (chunkSize > 0) {
                        result.write(buffer, 0, chunkSize);
                    }
                }
                bArr = result.toByteArray();
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e2) {
                    }
                }
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
        } catch (IOException e3) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e4) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e5) {
                }
            }
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
    return bArr;
}

From source file:Main.java

public static void saveJpegFile(String fileName, Bitmap bitmap) {
    // file// w  ww. j a v  a 2 s.c  o m
    File file = new File(extStorageDirectory, fileName + ".jpg");
    File fileDirectory = new File(extStorageDirectory);
    if (!fileDirectory.exists()) {
        fileDirectory.mkdir();
    }
    OutputStream outStream = null;
    try {
        outStream = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
        outStream.flush();
        outStream.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}