Example usage for java.io InputStreamReader close

List of usage examples for java.io InputStreamReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:org.apache.pig.impl.io.FileLocalizer.java

/**
 * Convert path from Windows convention to Unix convention. Invoked under
 * cygwin./* www . j a  v  a 2s.  c o m*/
 *
 * @param path
 *            path in Windows convention
 * @return path in Unix convention, null if fail
 */
static public String parseCygPath(String path, int style) {
    String[] command;
    if (style == STYLE_WINDOWS)
        command = new String[] { "cygpath", "-w", path };
    else
        command = new String[] { "cygpath", "-u", path };
    Process p = null;
    try {
        p = Runtime.getRuntime().exec(command);
    } catch (IOException e) {
        return null;
    }
    int exitVal = 0;
    try {
        exitVal = p.waitFor();
    } catch (InterruptedException e) {
        return null;
    }
    if (exitVal != 0)
        return null;
    String line = null;
    BufferedReader br = null;
    try {
        InputStreamReader isr = new InputStreamReader(p.getInputStream());
        br = new BufferedReader(isr);
        line = br.readLine();
        isr.close();
    } catch (IOException e) {
        return null;
    } finally {
        if (br != null)
            try {
                br.close();
            } catch (Exception e) {
            }
    }
    return line;
}

From source file:com.elastica.helper.FileUtility.java

/**
 * Read contents From Stream.//from   www  .  j  a v  a  2s  . c o  m
 *
 * @param   path
 *
 * @return  content
 *
 * @throws  IOException
 */
public static String readFromFile(final InputStream path) throws IOException {
    InputStreamReader fr = null;
    BufferedReader br = null;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        fr = new InputStreamReader(path);
        br = new BufferedReader(fr);

        String line;
        while ((line = br.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (fr != null) {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return stringBuilder.toString();
}

From source file:biz.bokhorst.xprivacy.Util.java

private static PublicKey getPublicKey(Context context) throws Throwable {
    // Read public key
    String sPublicKey = "";
    InputStreamReader isr = new InputStreamReader(context.getAssets().open("XPrivacy_public_key.txt"), "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    String line = br.readLine();//from   www.j  a v  a2 s  .  co m
    while (line != null) {
        if (!line.startsWith("-----"))
            sPublicKey += line;
        line = br.readLine();
    }
    br.close();
    isr.close();

    // Create public key
    byte[] bPublicKey = Base64.decode(sPublicKey, Base64.NO_WRAP);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec encodedPubKeySpec = new X509EncodedKeySpec(bPublicKey);
    return keyFactory.generatePublic(encodedPubKeySpec);
}

From source file:org.thoughtland.xlocation.Util.java

private static PublicKey getPublicKey(Context context) throws Throwable {
    // Read public key
    String sPublicKey = "";
    InputStreamReader isr = new InputStreamReader(context.getAssets().open("XLocation_public_key.txt"),
            "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    String line = br.readLine();/*from   w  w  w . j  a  v  a2s. c  o  m*/
    while (line != null) {
        if (!line.startsWith("-----"))
            sPublicKey += line;
        line = br.readLine();
    }
    br.close();
    isr.close();

    // Create public key
    byte[] bPublicKey = Base64.decode(sPublicKey, Base64.NO_WRAP);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec encodedPubKeySpec = new X509EncodedKeySpec(bPublicKey);
    return keyFactory.generatePublic(encodedPubKeySpec);
}

From source file:Main.java

@SuppressLint("HardwareIds")
static String getPhoneMacAddress(Context context) {
    String mac = "";

    InputStreamReader inputStreamReader = null;
    LineNumberReader lineNumberReader = null;
    try {/*w ww . j a  v  a 2 s.  co  m*/
        @SuppressLint("WifiManagerPotentialLeak")
        WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = manager.getConnectionInfo();
        mac = info.getMacAddress();

        if (TextUtils.isEmpty(mac)) {
            Process process = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
            inputStreamReader = new InputStreamReader(process.getInputStream());
            lineNumberReader = new LineNumberReader(inputStreamReader);
            String line = lineNumberReader.readLine();
            if (line != null) {
                mac = line.trim();
            }
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (lineNumberReader != null) {
            try {
                lineNumberReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    if (TextUtils.isEmpty(mac)) {
        mac = "na";
    }

    return mac;
}

From source file:com.clustercontrol.platform.PlatformPertial.java

public static void setupHostname() {
    String hostname = null;/*ww  w  .j a  v  a 2  s .  c  o m*/
    // hinemos.cfg???hostname?
    String etcDir = System.getProperty("hinemos.manager.etc.dir");
    if (etcDir != null) {
        File config = new File(etcDir, "hinemos.cfg");
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(config.getAbsolutePath());
            br = new BufferedReader(fr);

            String line;
            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (line.trim().startsWith("MANAGER_HOST")) {
                    hostname = line.split("=")[1];
                    break;
                }
            }
        } catch (FileNotFoundException e) {
            log.warn("configuration file not found." + config.getAbsolutePath(), e);
        } catch (IOException e) {
            log.warn("configuration read error." + config.getAbsolutePath(), e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }

            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                }
            }
        }
    }

    if (hostname == null || hostname.length() == 0) {
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        InputStreamReader is = null;
        BufferedReader br = null;

        try {
            process = runtime.exec("hostname");

            is = new InputStreamReader(process.getInputStream());
            br = new BufferedReader(is);
            process.waitFor();

            if (br != null) {
                hostname = br.readLine();
            }

        } catch (IOException | InterruptedException e) {
            log.warn("command execute error.", e);
        } finally {
            if (process != null) {
                process.destroy();
            }

            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }

            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }

    if (hostname == null) {
        hostname = "";
    }

    System.setProperty("hinemos.manager.hostname", hostname);
}

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

private static StringBuilder readModelFile(File file) throws IOException {
    StringBuilder result = new StringBuilder();
    FileInputStream fis = null;/* w ww  .ja v  a  2 s .c  o  m*/
    InputStreamReader reader = null;
    int size;
    try {
        char[] buffer = new char[1024];
        fis = new FileInputStream(file);

        FileWriter filewriter = new FileWriter("out");
        String encname = filewriter.getEncoding();
        filewriter.close();

        Charset cs = Charset.forName(encname);
        CharsetDecoder csd = cs.newDecoder();
        csd.onMalformedInput(CodingErrorAction.REPLACE);

        reader = new InputStreamReader(fis, csd);
        while ((size = reader.read(buffer, 0, 1024)) > 0) {
            result.append(buffer, 0, size);
        }
    } catch (Exception e) {
        // System.out.println(encoding);
        e.printStackTrace();
    } finally {
        if (fis != null) {
            fis.close();
        }

        if (reader != null) {
            reader.close();
        }
    }

    return result;
}

From source file:cd.education.data.collector.android.utilities.FileUtils.java

public static HashMap<String, String> parseXML(File xmlFile) {
    HashMap<String, String> fields = new HashMap<String, String>();
    InputStream is;//w  w  w.  j  a  va  2  s . co  m
    try {
        is = new FileInputStream(xmlFile);
    } catch (FileNotFoundException e1) {
        throw new IllegalStateException(e1);
    }

    InputStreamReader isr;
    try {
        isr = new InputStreamReader(is, "UTF-8");
    } catch (UnsupportedEncodingException uee) {
        Log.w(t, "UTF 8 encoding unavailable, trying default encoding");
        isr = new InputStreamReader(is);
    }

    if (isr != null) {

        Document doc;
        try {
            doc = XFormParser.getXMLDocument(isr);
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalStateException("Unable to parse XML document", e);
        } finally {
            try {
                isr.close();
            } catch (IOException e) {
                Log.w(t, xmlFile.getAbsolutePath() + " Error closing form reader");
                e.printStackTrace();
            }
        }

        String xforms = "http://www.w3.org/2002/xforms";
        String html = doc.getRootElement().getNamespace();

        Element head = doc.getRootElement().getElement(html, "head");
        Element title = head.getElement(html, "title");
        if (title != null) {
            fields.put(TITLE, XFormParser.getXMLText(title, true));
        }

        Element model = getChildElement(head, "model");
        Element cur = getChildElement(model, "instance");

        int idx = cur.getChildCount();
        int i;
        for (i = 0; i < idx; ++i) {
            if (cur.isText(i))
                continue;
            if (cur.getType(i) == Node.ELEMENT) {
                break;
            }
        }

        if (i < idx) {
            cur = cur.getElement(i); // this is the first data element
            String id = cur.getAttributeValue(null, "id");
            String xmlns = cur.getNamespace();

            String version = cur.getAttributeValue(null, "version");
            String uiVersion = cur.getAttributeValue(null, "uiVersion");
            if (uiVersion != null) {
                // pre-OpenRosa 1.0 variant of spec
                Log.e(t, "Obsolete use of uiVersion -- IGNORED -- only using version: " + version);
            }

            fields.put(FORMID, (id == null) ? xmlns : id);
            fields.put(VERSION, (version == null) ? null : version);
        } else {
            throw new IllegalStateException(xmlFile.getAbsolutePath() + " could not be parsed");
        }
        try {
            Element submission = model.getElement(xforms, "submission");
            String submissionUri = submission.getAttributeValue(null, "action");
            fields.put(SUBMISSIONURI, (submissionUri == null) ? null : submissionUri);
            String base64RsaPublicKey = submission.getAttributeValue(null, "base64RsaPublicKey");
            fields.put(BASE64_RSA_PUBLIC_KEY,
                    (base64RsaPublicKey == null || base64RsaPublicKey.trim().length() == 0) ? null
                            : base64RsaPublicKey.trim());
        } catch (Exception e) {
            Log.i(t, xmlFile.getAbsolutePath() + " does not have a submission element");
            // and that's totally fine.
        }

    }
    return fields;
}

From source file:Main.java

public static String readStringFromFile(String fileName, boolean addEnterLindEnd) {
    StringBuilder result = new StringBuilder();
    FileInputStream fip = null;/*from   www  .ja  v  a  2s . c om*/
    InputStreamReader inputReader = null;
    BufferedReader bufReader = null;
    try {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            fip = new FileInputStream(file);
            inputReader = new InputStreamReader(fip);
            bufReader = new BufferedReader(inputReader);
            String line = "";
            while ((line = bufReader.readLine()) != null) {
                if (addEnterLindEnd) {
                    result.append(line + "\n");
                } else {
                    result.append(line);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != bufReader) {
                bufReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (null != inputReader) {
                inputReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (null != fip) {
                fip.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result.toString();
}

From source file:org.apache.jmeter.save.SaveService.java

/**
 * Read results from JTL file./*from www .  j av a  2 s . c  o m*/
 *
 * @param reader of the file
 * @param resultCollectorHelper helper class to enable TestResultWrapperConverter to deliver the samples
 * @throws IOException if an I/O error occurs
 */
public static void loadTestResults(InputStream reader, ResultCollectorHelper resultCollectorHelper)
        throws IOException {
    // Get the InputReader to use
    InputStreamReader inputStreamReader = getInputStreamReader(reader);
    DataHolder dh = JTLSAVER.newDataHolder();
    dh.put(RESULTCOLLECTOR_HELPER_OBJECT, resultCollectorHelper); // Allow TestResultWrapper to feed back the samples
    // This is effectively the same as saver.fromXML(InputStream) except we get to provide the DataHolder
    // Don't know why there is no method for this in the XStream class
    JTLSAVER.unmarshal(new XppDriver().createReader(reader), null, dh);
    inputStreamReader.close();
}