Example usage for java.io DataInputStream close

List of usage examples for java.io DataInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:com.chintans.venturebox.util.Utils.java

private static String getStreamLines(final InputStream is) {
    String out = null;/*from w  w w .  j av a 2s  .  c o m*/
    StringBuffer buffer = null;
    final DataInputStream dis = new DataInputStream(is);

    try {
        if (dis.available() > 0) {
            buffer = new StringBuffer(dis.readLine());
            while (dis.available() > 0) {
                buffer.append("\n").append(dis.readLine());
            }
        }
        dis.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    if (buffer != null) {
        out = buffer.toString();
    }
    return out;
}

From source file:com.cedarsoft.crypt.X509Support.java

/**
 * Reads a private key form a url//from w  w  w  .  ja  va 2s  .  co  m
 *
 * @param privateKeyUrl the url containing the private key
 * @return the read private key
 *
 * @throws IOException if any.
 * @throws GeneralSecurityException
 *                             if any.
 */
@Nullable
public static RSAPrivateKey readPrivateKey(@Nullable URL privateKeyUrl)
        throws IOException, GeneralSecurityException {
    //If a null url is given - just return null
    if (privateKeyUrl == null) {
        return null;
    }

    //We have an url --> return it
    DataInputStream in = new DataInputStream(privateKeyUrl.openStream());
    try {
        byte[] keyBytes = IOUtils.toByteArray(in);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);

        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(keyBytes);
        return (RSAPrivateKey) keyFactory.generatePrivate(privSpec);
    } finally {
        in.close();
    }
}

From source file:com.google.android.mms.transaction.HttpUtils.java

/**
 * A helper method to send or retrieve data through HTTP protocol.
 *
 * @param token The token to identify the sending progress.
 * @param url The URL used in a GET request. Null when the method is
 *         HTTP_POST_METHOD.//from   ww  w .jav a 2  s.  c  om
 * @param pdu The data to be POST. Null when the method is HTTP_GET_METHOD.
 * @param method HTTP_POST_METHOD or HTTP_GET_METHOD.
 * @return A byte array which contains the response data.
 *         If an HTTP error code is returned, an IOException will be thrown.
 * @throws IOException if any error occurred on network interface or
 *         an HTTP error code(>=400) returned from the server.
 */
public static byte[] httpConnection(Context context, long token, String url, byte[] pdu, int method,
        boolean isProxySet, String proxyHost, int proxyPort) throws IOException {
    if (url == null) {
        throw new IllegalArgumentException("URL must not be null.");
    }

    if (LOCAL_LOGV) {
        Log.v(TAG, "httpConnection: params list");
        Log.v(TAG, "\ttoken\t\t= " + token);
        Log.v(TAG, "\turl\t\t= " + url);
        Log.v(TAG, "\tmethod\t\t= "
                + ((method == HTTP_POST_METHOD) ? "POST" : ((method == HTTP_GET_METHOD) ? "GET" : "UNKNOWN")));
        Log.v(TAG, "\tisProxySet\t= " + isProxySet);
        Log.v(TAG, "\tproxyHost\t= " + proxyHost);
        Log.v(TAG, "\tproxyPort\t= " + proxyPort);
        // TODO Print out binary data more readable.
        //Log.v(TAG, "\tpdu\t\t= " + Arrays.toString(pdu));
    }

    AndroidHttpClient client = null;

    try {
        // Make sure to use a proxy which supports CONNECT.
        URI hostUrl = new URI(url);
        HttpHost target = new HttpHost(hostUrl.getHost(), hostUrl.getPort(), HttpHost.DEFAULT_SCHEME_NAME);

        client = createHttpClient(context);
        HttpRequest req = null;
        switch (method) {
        case HTTP_POST_METHOD:
            ProgressCallbackEntity entity = new ProgressCallbackEntity(context, token, pdu);
            // Set request content type.
            entity.setContentType("application/vnd.wap.mms-message");

            HttpPost post = new HttpPost(url);
            post.setEntity(entity);
            req = post;
            break;
        case HTTP_GET_METHOD:
            req = new HttpGet(url);
            break;
        default:
            Log.e(TAG, "Unknown HTTP method: " + method + ". Must be one of POST[" + HTTP_POST_METHOD
                    + "] or GET[" + HTTP_GET_METHOD + "].");
            return null;
        }

        // Set route parameters for the request.
        HttpParams params = client.getParams();
        if (isProxySet) {
            ConnRouteParams.setDefaultProxy(params, new HttpHost(proxyHost, proxyPort));
        }
        req.setParams(params);

        // Set necessary HTTP headers for MMS transmission.
        req.addHeader(HDR_KEY_ACCEPT, HDR_VALUE_ACCEPT);
        {
            String xWapProfileTagName = MmsConfig.getUaProfTagName();
            String xWapProfileUrl = MmsConfig.getUaProfUrl();

            if (xWapProfileUrl != null) {
                if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
                    Log.d(LogTag.TRANSACTION, "[HttpUtils] httpConn: xWapProfUrl=" + xWapProfileUrl);
                }
                req.addHeader(xWapProfileTagName, xWapProfileUrl);
            }
        }

        // Extra http parameters. Split by '|' to get a list of value pairs.
        // Separate each pair by the first occurrence of ':' to obtain a name and
        // value. Replace the occurrence of the string returned by
        // MmsConfig.getHttpParamsLine1Key() with the users telephone number inside
        // the value.
        String extraHttpParams = MmsConfig.getHttpParams();

        if (extraHttpParams != null) {
            String line1Number = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
                    .getLine1Number();
            String line1Key = MmsConfig.getHttpParamsLine1Key();
            String paramList[] = extraHttpParams.split("\\|");

            for (String paramPair : paramList) {
                String splitPair[] = paramPair.split(":", 2);

                if (splitPair.length == 2) {
                    String name = splitPair[0].trim();
                    String value = splitPair[1].trim();

                    if (line1Key != null) {
                        value = value.replace(line1Key, line1Number);
                    }
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(value)) {
                        req.addHeader(name, value);
                    }
                }
            }
        }
        req.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);

        HttpResponse response = client.execute(target, req);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) { // HTTP 200 is success.
            throw new IOException("HTTP error: " + status.getReasonPhrase());
        }

        HttpEntity entity = response.getEntity();
        byte[] body = null;
        if (entity != null) {
            try {
                if (entity.getContentLength() > 0) {
                    body = new byte[(int) entity.getContentLength()];
                    DataInputStream dis = new DataInputStream(entity.getContent());
                    try {
                        dis.readFully(body);
                    } finally {
                        try {
                            dis.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Error closing input stream: " + e.getMessage());
                        }
                    }
                }
            } finally {
                if (entity != null) {
                    entity.consumeContent();
                }
            }
        }
        return body;
    } catch (URISyntaxException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalStateException e) {
        handleHttpConnectionException(e, url);
    } catch (IllegalArgumentException e) {
        handleHttpConnectionException(e, url);
    } catch (SocketException e) {
        handleHttpConnectionException(e, url);
    } catch (Exception e) {
        handleHttpConnectionException(e, url);
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return null;
}

From source file:org.digitalcampus.oppia.utils.FileUtils.java

public static String readFile(String file) throws IOException {
    FileInputStream fstream = new FileInputStream(file);
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;// w ww.  j ava  2  s.  c  o  m
    StringBuilder stringBuilder = new StringBuilder();
    while ((strLine = br.readLine()) != null) {
        stringBuilder.append(strLine);
    }
    in.close();
    return stringBuilder.toString();
}

From source file:org.digitalcampus.oppia.utils.FileUtils.java

public static String readFile(InputStream fileStream) throws IOException {
    DataInputStream in = new DataInputStream(fileStream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;//w ww .  j a va  2 s. c o  m
    StringBuilder stringBuilder = new StringBuilder();
    while ((strLine = br.readLine()) != null) {
        stringBuilder.append(strLine);
    }
    in.close();
    return stringBuilder.toString();
}

From source file:Main.java

public static void execCmd(String cmd) {
    DataOutputStream dos = null;/*from  ww  w . j a  v a2 s  .  com*/
    DataInputStream dis = null;
    try {
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());
        cmd += "\n";
        dos.writeBytes(cmd);
        dos.flush();
        dos.writeBytes("exit\n");
        dos.flush();
        p.waitFor();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        try {
            if (dos != null)
                dos.close();
            if (dis != null)
                dis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

/**
 * Reads in model 83 points and returns a double array float containing the
 * coordinates x & y.//from   ww  w . j  a v  a2 s .  c  o  m
 */
public static float[][][] readBinSFSV(String dir, String fileName) {
    float[][][] array3D = new float[60][83][3];
    float x;
    File sdLien = Environment.getExternalStorageDirectory();
    File inFile = new File(sdLien + File.separator + dir + File.separator + fileName);
    Log.d(TAG, "path of file : " + inFile);
    if (!inFile.exists()) {
        throw new RuntimeException("File doesn't exist");
    }
    DataInputStream in = null;
    try {
        in = new DataInputStream(new FileInputStream(inFile));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        for (int k = 0; k < 3; k++) {
            for (int j = 0; j < 83; j++) {
                for (int i = 0; i < 60; i++) {
                    x = in.readFloat();
                    array3D[i][j][k] = x;
                }
            }
        }
    } catch (EOFException e) {
        try {
            Log.d(TAG, "close");
            in.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try { //free ressources
                Log.d(TAG, "close");
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return array3D;
}

From source file:com.ccoe.build.core.utils.FileUtils.java

public static String readFile(File file) {
    BufferedReader br = null;/*  w  w  w.j  av  a 2 s  .  c  om*/
    DataInputStream in = null;
    StringBuffer sBuffer = new StringBuffer();

    try {
        in = new DataInputStream(new FileInputStream(file));
        br = new BufferedReader(new InputStreamReader(in));

        String sCurrentLine = null;

        while ((sCurrentLine = br.readLine()) != null) {
            sBuffer.append(sCurrentLine);
            sBuffer.append("\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return sBuffer.toString().trim();
}

From source file:com.gson.util.HttpKit.java

/**
 * //from ww  w  . j a  v  a2 s  .  c om
 * @param url
 * @param params
 * @param file
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
public static String upload(String url, File file)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ?  
    StringBuffer bufferRes = null;
    URL urlGet = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

    OutputStream out = new DataOutputStream(conn.getOutputStream());
    byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ??  
    StringBuilder sb = new StringBuilder();
    sb.append("--");
    sb.append(BOUNDARY);
    sb.append("\r\n");
    sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
    sb.append("Content-Type:application/octet-stream\r\n\r\n");
    byte[] data = sb.toString().getBytes();
    out.write(data);
    DataInputStream fs = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] bufferOut = new byte[1024];
    while ((bytes = fs.read(bufferOut)) != -1) {
        out.write(bufferOut, 0, bytes);
    }
    out.write("\r\n".getBytes()); //  
    fs.close();
    out.write(end_data);
    out.flush();
    out.close();

    // BufferedReader???URL?  
    InputStream in = conn.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (conn != null) {
        // 
        conn.disconnect();
    }
    return bufferRes.toString();
}

From source file:com.hichengdai.qlqq.front.util.HttpKit.java

/**
 * //from  w w  w.j  a v  a2  s . com
 * 
 * @param url
 * @param params
 * @param file
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
public static String upload(String url, File file)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ?
    StringBuffer bufferRes = null;
    URL urlGet = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

    OutputStream out = new DataOutputStream(conn.getOutputStream());
    byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ??
    StringBuilder sb = new StringBuilder();
    sb.append("--");
    sb.append(BOUNDARY);
    sb.append("\r\n");
    sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
    sb.append("Content-Type:application/octet-stream\r\n\r\n");
    byte[] data = sb.toString().getBytes();
    out.write(data);
    DataInputStream fs = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] bufferOut = new byte[1024];
    while ((bytes = fs.read(bufferOut)) != -1) {
        out.write(bufferOut, 0, bytes);
    }
    out.write("\r\n".getBytes()); // 
    fs.close();
    out.write(end_data);
    out.flush();
    out.close();

    // BufferedReader???URL?
    InputStream in = conn.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (conn != null) {
        // 
        conn.disconnect();
    }
    return bufferRes.toString();
}