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:com.headswilllol.basiclauncher.Launcher.java

public static String convertStreamToString(InputStream is, boolean newlines) {
    /*//  w  ww  . j  a v  a  2s . c  o m
     * Why don't people update to Java 7? Like, seriously. It's November of 2013 as of
     * typing this, Java 8 is some 4 months away, and there are still people who use my
     * code who are running Java 6. Like 5% of the users are using an obsolete version
     * of Java from 2006. It's not like it's even that hard to update. Honestly, you
     * just click a couple of buttons, check a box, and bam, you've made my job easier.
     * And yet, because these people are so lazy, I'm forced to compile with Java 6 to
     * accommodate for this ridiculous minority. I say this because I could accomplish
     * what this try-block does in about 2 lines of code, but nope, gotta use Java 6.
     * I'm really psyched for lambda expressions in Java 8, but I can't even use those
     * until Java 9 is out, because there'll be those morons who just refuse to update
     * past 7. It's stupid, it really is.</rant>
     */
    InputStreamReader isr = new InputStreamReader(is);
    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(isr);
    try {
        String read = br.readLine();
        while (read != null) {
            sb.append(read);
            if (newlines)
                sb.append("\n");
            read = br.readLine();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        //createExceptionLog(); // I'm leaving this here as a lesson to my future self.
        progress = "Failed to get output from launch command";
        fail = "Errors occurred; see console for details";
        launcher.paintImmediately(0, 0, width, height);
    } finally {
        try {
            isr.close();
            br.close();
        } catch (Exception ex) {
            // dunno why this would happen anyway, but whatever
            ex.printStackTrace();
        }
    }
    return sb.toString();
}

From source file:BRHInit.java

public JSONObject json_rpc(String method, JSONArray params) throws Exception {
    URLConnection conn = rpc_url.openConnection();
    if (cookie != null)
        conn.addRequestProperty("cookie", cookie);

    JSONObject request = new JSONObject();

    request.put("id", false);
    request.put("method", method);
    request.put("params", params);

    conn.setDoOutput(true);//from   w w  w . ja  v  a  2 s .  co  m
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    try {
        wr.write(request.toString());
        wr.flush();
    } finally {
        wr.close();
    }

    // Get the response
    InputStreamReader rd = new InputStreamReader(conn.getInputStream());
    try {
        JSONTokener tokener = new JSONTokener(rd);
        return (JSONObject) tokener.nextValue();
    } finally {
        rd.close();
    }
}

From source file:com.esp8266.mkspiffs.ESP8266FS.java

private int listenOnProcess(String[] arguments) {
    try {/*  w  ww.  j ava2  s  .  c o m*/
        final Process p = ProcessUtils.exec(arguments);
        Thread thread = new Thread() {
            public void run() {
                try {
                    InputStreamReader reader = new InputStreamReader(p.getInputStream());
                    int c;
                    while ((c = reader.read()) != -1)
                        System.out.print((char) c);
                    reader.close();

                    reader = new InputStreamReader(p.getErrorStream());
                    while ((c = reader.read()) != -1)
                        System.err.print((char) c);
                    reader.close();
                } catch (Exception e) {
                }
            }
        };
        thread.start();
        int res = p.waitFor();
        thread.join();
        return res;
    } catch (Exception e) {
        return -1;
    }
}

From source file:com.sytecso.jbpm.client.rs.JbpmRestTemplate.java

private String read(InputStream is) throws Exception {
    String responseString;/* ww w .  ja v a  2s  . com*/
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    StringBuilder stringBuilder = new StringBuilder();
    String line = br.readLine();
    while (line != null) {
        stringBuilder.append(line);
        line = br.readLine();
    }
    responseString = stringBuilder.toString();
    isr.close();
    br.close();
    return responseString;
}

From source file:net.unicon.academus.spell.SpellCheckerServlet.java

private void printResource(PrintWriter out, String resource) throws IOException {
    InputStreamReader is = new InputStreamReader(ctx.getResourceAsStream(resource));

    char[] buf = new char[4096];
    int r = 0;// w  w w .  j  a va  2s .  c  o m
    while ((r = is.read(buf, 0, buf.length)) != -1) {
        out.write(buf, 0, r);
    }
    is.close();
    out.flush();
}

From source file:org.apache.camel.dataformat.csv.CsvIteratorTest.java

@Test
public void normalCycle(@Injectable final InputStreamReader reader, @Injectable final CSVParser parser)
        throws IOException {
    new Expectations() {
        {//from   w w w.j av  a 2  s. com
            parser.getLine();
            result = new String[] { "1" };

            parser.getLine();
            result = new String[] { "2" };

            parser.getLine();
            result = null;

            // The reader will be closed when there is nothing left
            reader.close();
        }
    };

    @SuppressWarnings("resource")
    CsvIterator<List<String>> iterator = new CsvIterator<List<String>>(parser, reader,
            CsvLineConverters.getListConverter());
    Assert.assertTrue(iterator.hasNext());
    Assert.assertEquals(Arrays.asList("1"), iterator.next());

    Assert.assertTrue(iterator.hasNext());
    Assert.assertEquals(Arrays.asList("2"), iterator.next());

    Assert.assertFalse(iterator.hasNext());

    try {
        iterator.next();
        Assert.fail("exception expected");
    } catch (NoSuchElementException e) {
        // okay
    }
}

From source file:com.microsoft.speech.tts.OxfordAuthentication.java

private void HttpPost(String AccessTokenUri, String requestDetails) {
    InputStream inSt = null;// w w w.  j  a  va 2  s.c  om
    HttpsURLConnection webRequest = null;

    this.token = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        webRequest.setRequestMethod("POST");

        byte[] bytes = requestDetails.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        // parse the access token from the json format
        String result = strBuffer.toString();
        JSONObject jsonRoot = new JSONObject(result);
        this.token = new OxfordAccessToken();

        if (jsonRoot.has("access_token")) {
            this.token.access_token = jsonRoot.getString("access_token");
        }

        if (jsonRoot.has("token_type")) {
            this.token.token_type = jsonRoot.getString("token_type");
        }

        if (jsonRoot.has("expires_in")) {
            this.token.expires_in = jsonRoot.getString("expires_in");
        }

        if (jsonRoot.has("scope")) {
            this.token.scope = jsonRoot.getString("scope");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:com.sds.acube.ndisc.xmigration.util.XNDiscMigUtil.java

/**
 * XMigration ? ?//from   w  w  w.j a  va  2 s  .  co  m
 */
private static void readVersionFromFile() {
    XMigration_PublishingVersion = "<unknown>";
    XMigration_PublishingDate = "<unknown>";
    InputStreamReader isr = null;
    LineNumberReader lnr = null;
    try {
        isr = new InputStreamReader(
                XNDiscMigUtil.class.getResourceAsStream("/com/sds/acube/ndisc/xmigration/version.txt"));
        if (isr != null) {
            lnr = new LineNumberReader(isr);
            String line = null;
            do {
                line = lnr.readLine();
                if (line != null) {
                    if (line.startsWith("Publishing-Version=")) {
                        XMigration_PublishingVersion = line
                                .substring("Publishing-Version=".length(), line.length()).trim();
                    } else if (line.startsWith("Publishing-Date=")) {
                        XMigration_PublishingDate = line.substring("Publishing-Date=".length(), line.length())
                                .trim();
                    }
                }
            } while (line != null);
            lnr.close();
        }
    } catch (IOException ioe) {
        XMigration_PublishingVersion = "<unknown>";
        XMigration_PublishingDate = "<unknown>";
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
            if (isr != null) {
                isr.close();
            }
        } catch (IOException ioe) {
        }
    }
}

From source file:com.stratio.explorer.interpreter.InterpreterFactory.java

private String loadFromFile(String path) {

    File fileToRead = new File(path);
    if (!fileToRead.exists()) {
        // nothing to read
        return "empty";
    }/*  w ww  . j a  v  a2s  .  c  om*/
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(fileToRead);

        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader bufferedReader = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line).append(System.lineSeparator());
        }
        isr.close();
        fis.close();
        return sb.toString();

    } catch (FileNotFoundException e) {
        return "input stream error " + e;
    } catch (IOException e) {
        return "io exception " + e;
    }

}

From source file:de.uni_luebeck.inb.knowarc.usecases.invocation.UseCaseInvocation.java

@SuppressWarnings("unchecked")
public void setInput(String inputName, ReferenceService referenceService, T2Reference t2Reference)
        throws InvocationException {
    if (t2Reference == null) {
        throw new InvocationException("No input specified for " + inputName);
    }/*from   w w w  . j a  v  a 2 s . co  m*/
    ScriptInputUser input = (ScriptInputUser) usecase.getInputs().get(inputName);
    if (input.isList()) {
        IdentifiedList<T2Reference> listOfReferences = (IdentifiedList<T2Reference>) referenceService
                .getListService().getList(t2Reference);

        if (!input.isConcatenate()) {
            // this is a list input (not concatenated)
            // so write every element to its own temporary file
            // and create a filelist file

            // we need to write the list elements to temporary files
            ScriptInputUser listElementTemp = new ScriptInputUser();
            listElementTemp.setBinary(input.isBinary());
            listElementTemp.setTempFile(true);

            String lineEndChar = "\n";
            if (!input.isFile() && !input.isTempFile()) {
                lineEndChar = " ";
            }

            String listFileContent = "";
            String filenamesFileContent = "";
            // create a list of all temp file names
            for (T2Reference cur : listOfReferences) {
                String tmp = setOneInput(referenceService, cur, listElementTemp);
                listFileContent += tmp + lineEndChar;
                int ind = tmp.lastIndexOf('/');
                if (ind == -1) {
                    ind = tmp.lastIndexOf('\\');
                }
                if (ind != -1) {
                    tmp = tmp.substring(ind + 1);
                }
                filenamesFileContent += tmp + lineEndChar;
            }

            // how do we want the listfile to be stored?
            ScriptInputUser listFile = new ScriptInputUser();
            listFile.setBinary(false); // since its a list file
            listFile.setFile(input.isFile());
            listFile.setTempFile(input.isTempFile());
            listFile.setTag(input.getTag());
            T2Reference listFileContentReference = referenceService.register(listFileContent, 0, true,
                    invocationContext);

            tags.put(listFile.getTag(), setOneInput(referenceService, listFileContentReference, listFile));

            listFile.setTag(input.getTag() + "_NAMES");
            T2Reference filenamesFileContentReference = referenceService.register(filenamesFileContent, 0, true,
                    null);
            tags.put(listFile.getTag(), setOneInput(referenceService, filenamesFileContentReference, listFile));
        } else {
            try {
                // first, concatenate all data
                if (input.isBinary()) {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    BufferedWriter outputWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
                    for (T2Reference cur : listOfReferences) {
                        InputStreamReader inputReader = new InputStreamReader(
                                getAsStream(referenceService, cur));
                        IOUtils.copyLarge(inputReader, outputWriter);
                        inputReader.close();
                    }
                    outputWriter.close();
                    T2Reference binaryReference = referenceService.register(outputStream.toByteArray(), 0, true,
                            invocationContext);
                    tags.put(input.getTag(), setOneInput(referenceService, binaryReference, input));
                } else {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    BufferedWriter outputWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
                    for (T2Reference cur : listOfReferences) {
                        InputStreamReader inputReader = new InputStreamReader(
                                getAsStream(referenceService, cur));
                        IOUtils.copyLarge(inputReader, outputWriter);
                        outputWriter.write(" ");
                        inputReader.close();
                    }
                    outputWriter.close();
                    T2Reference binaryReference = referenceService.register(outputStream.toByteArray(), 0, true,
                            invocationContext);
                    tags.put(input.getTag(), setOneInput(referenceService, binaryReference, input));
                }
            } catch (IOException e) {
                throw new InvocationException(e);
            }
        }
    } else {
        tags.put(input.getTag(), setOneInput(referenceService, t2Reference, input));
    }
}