Example usage for java.io InputStreamReader read

List of usage examples for java.io InputStreamReader read

Introduction

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

Prototype

public int read() throws IOException 

Source Link

Document

Reads a single character.

Usage

From source file:org.mzd.shap.analysis.metagene.Metagene2008ToXML.java

public static void main(String[] args) throws IOException, BeanIOException {
    if (args.length != 2) {
        System.out.println("[input sequence] [output orfs]");
        System.exit(1);/*www.j a  v a 2s.c  om*/
    }

    Process p = Runtime.getRuntime().exec("metagene " + args[0]);
    try {
        synchronized (p) {
            StringWriter sw = new StringWriter();
            InputStreamReader isr = new InputStreamReader(p.getInputStream());
            int retVal;
            while (true) {
                p.wait(100);
                while (isr.ready()) {
                    sw.write(isr.read());
                }
                try {
                    retVal = p.exitValue();
                    break;
                } catch (IllegalThreadStateException ex) {
                    /*...*/}
            }

            // Just make sure stdout is completely empty.
            while (isr.ready()) {
                sw.write(isr.read());
            }

            if (retVal != 0) {
                System.out.println("Non-zero exist status [" + retVal + "]");
                InputStream is = null;
                try {
                    is = p.getErrorStream();
                    while (is.available() > 0) {
                        System.out.write(is.read());
                    }
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            } else {
                new Metagene2008ToXML().convert(sw.toString(), new File(args[1]));
            }

            System.exit(retVal);
        }
    } catch (InterruptedException ex) {
        /*...*/}
}

From source file:com.annuletconsulting.homecommand.server.HomeCommand.java

/**
 * This class will accept commands from a node in each room. For it to react to events on the server
 * computer, it must be also running as a node.  However the server can cause all nodes to react
 * to an event happening on any node, such as an email or text arriving.  A call on a node device
 * could pause all music devices, for example.
 * //from w  ww  . jav  a2s  .  co  m
 * @param args
 */
public static void main(String[] args) {
    try {
        socket = Integer.parseInt(HomeComandProperties.getInstance().getServerPort());
        nonJavaUserModulesPath = HomeComandProperties.getInstance().getNonJavaUserDir();
    } catch (Exception exception) {
        System.out.println("Error loading from properties file.");
        exception.printStackTrace();
    }
    try {
        sharedKey = HomeComandProperties.getInstance().getSharedKey();
        if (sharedKey == null)
            System.out.println("shared_key is null, commands without valid signatures will be processed.");
    } catch (Exception exception) {
        System.out.println("shared_key not found in properties file.");
        exception.printStackTrace();
    }
    try {
        if (args.length > 0) {
            String arg0 = args[0];
            if (arg0.equals("help") || arg0.equals("?") || arg0.equals("usage") || arg0.equals("-help")
                    || arg0.equals("-?")) {
                System.out.println(
                        "The defaults can be changed by editing the HomeCommand.properties file, or you can override them temporarily using command line options.");
                System.out.println("\nHome Command Server command line overrride usage:");
                System.out.println(
                        "hcserver [server_port] [java_user_module_directory] [non_java_user_module_directory]"); //TODO make hcserver.sh
                System.out.println("\nDefaults:");
                System.out.println("server_port: " + socket);
                System.out.println("java_user_module_directory: " + userModulesPath);
                System.out.println("non_java_user_module_directory: " + nonJavaUserModulesPath);
                System.out.println("\n2013 | Annulet, LLC");
            }
            socket = Integer.parseInt(arg0);
        }
        if (args.length > 1)
            userModulesPath = args[1];
        if (args.length > 2)
            nonJavaUserModulesPath = args[2];

        System.out.println("Config loaded, initializing modules.");
        modules.add(new HueLightModule());
        System.out.println("HueLightModule initialized.");
        modules.add(new QuestionModule());
        System.out.println("QuestionModule initialized.");
        modules.add(new MathModule());
        System.out.println("MathModule initialized.");
        modules.add(new MusicModule());
        System.out.println("MusicModule initialized.");
        modules.add(new NonCopyrightInfringingGenericSpaceExplorationTVShowModule());
        System.out.println("NonCopyrightInfringingGenericSpaceExplorationTVShowModule initialized.");
        modules.add(new HelpModule());
        System.out.println("HelpModule initialized.");
        modules.add(new SetUpModule());
        System.out.println("SetUpModule initialized.");
        modules.addAll(NonJavaUserModuleLoader.loadModulesAt(nonJavaUserModulesPath));
        System.out.println("NonJavaUserModuleLoader initialized.");
        ServerSocket serverSocket = new ServerSocket(socket);
        System.out.println("Listening...");
        while (!end) {
            Socket socket = serverSocket.accept();
            InputStreamReader isr = new InputStreamReader(socket.getInputStream());
            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
            int character;
            StringBuffer inputStrBuffer = new StringBuffer();
            while ((character = isr.read()) != 13) {
                inputStrBuffer.append((char) character);
            }
            System.out.println(inputStrBuffer.toString());
            String[] cmd; // = inputStrBuffer.toString().split(" ");
            String result = "YOUR REQUEST WAS NOT VALID JSON";
            if (inputStrBuffer.substring(0, 1).equals("{")) {
                nodeType = extractElement(inputStrBuffer.toString(), "node_type");
                if (sharedKey != null) {
                    if (validateSignature(extractElement(inputStrBuffer.toString(), "time_stamp"),
                            extractElement(inputStrBuffer.toString(), "signature"))) {
                        if ("Y".equalsIgnoreCase(extractElement(inputStrBuffer.toString(), "cmd_encoded")))
                            cmd = decryptCommand(extractElement(inputStrBuffer.toString(), "command"));
                        else
                            cmd = extractElement(inputStrBuffer.toString(), "command").split(" ");
                        result = getResult(cmd);
                    } else
                        result = "YOUR SIGNATURE DID NOT MATCH, CHECK SHARED KEY";
                } else {
                    cmd = extractElement(inputStrBuffer.toString(), "command").split(" ");
                    result = getResult(cmd);
                }
            }
            System.out.println(result);
            output.print(result);
            output.print((char) 13);
            output.close();
            isr.close();
            socket.close();
        }
        serverSocket.close();
        System.out.println("Shutting down.");
    } catch (Exception exception) {
        exception.printStackTrace();
    }
}

From source file:Main.java

public static String readStreamWithoutBuffer(InputStream src) throws IOException {
    StringBuilder sb = new StringBuilder();
    InputStreamReader is = new InputStreamReader(src);
    char c = (char) is.read();
    while (c != -1) {
        sb.append(c);/* www . j av a2 s .c om*/
        c = (char) is.read();
    }
    return sb.toString();
}

From source file:Main.java

public static String readStreamToString(InputStream in, String encoding) throws IOException {
    StringBuffer b = new StringBuffer();
    InputStreamReader r = new InputStreamReader(in, encoding);
    int c;//from   ww w .  j  av  a  2  s  . com
    while ((c = r.read()) != -1) {
        b.append((char) c);
    }
    return b.toString();
}

From source file:Main.java

static String downloadHtml(String urlString) {
    StringBuffer buffer = new StringBuffer();

    try {//from  w ww. java  2 s  .c om
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        HttpURLConnection.setFollowRedirects(true);
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        String encoding = conn.getContentEncoding();
        InputStream inStr = null;

        if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
            inStr = new GZIPInputStream(conn.getInputStream());
        } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
            inStr = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
        } else {
            inStr = conn.getInputStream();
        }
        int ptr = 0;
        InputStreamReader inStrReader = new InputStreamReader(inStr, Charset.forName("GB2312"));

        while ((ptr = inStrReader.read()) != -1) {
            buffer.append((char) ptr);
        }
        inStrReader.close();
        conn.disconnect();
        inStr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return buffer.toString();
}

From source file:Main.java

public static String getContent(InputStreamReader reader) throws IOException {
    StringBuffer content = new StringBuffer();
    int next = -1;
    while ((next = reader.read()) >= 0) {
        content.append((char) next);
    }/*from   w  w  w .  j a va  2  s .  c  o  m*/
    return content.toString();
}

From source file:Main.java

/**
 * The method read a XML from URL, skips irrelevant chars and serves back the content as string. 
 * @param inputStream// w ww.j  a  v  a 2s . com
 * @return String : content of a file 
 * @throws IOException
 */
public static String getURLToString(URL url) throws IOException {
    InputStreamReader inputStream = new InputStreamReader(url.openStream(), "ISO-8859-1");
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        int i = inputStream.read();
        while (i != -1) {
            if (i != TAB && i != NL && i != CR)
                byteArrayOutputStream.write(i);
            i = inputStream.read();
        }

        String x = byteArrayOutputStream.toString("UTF-8");
        return x;

    } catch (IOException e) {
        e.printStackTrace();
        return "";

    } finally {
        inputStream.close();
    }
}

From source file:PKCS12Import.java

static char[] readPassphrase() throws IOException {
    InputStreamReader in = new InputStreamReader(System.in);

    char[] cbuf = new char[256];
    int i = 0;/*from w  w  w .j a va2 s  . com*/

    readchars: while (i < cbuf.length) {
        char c = (char) in.read();
        switch (c) {
        case '\r':
            break readchars;
        case '\n':
            break readchars;
        default:
            cbuf[i++] = c;
        }
    }

    char[] phrase = new char[i];
    System.arraycopy(cbuf, 0, phrase, 0, i);
    return phrase;
}

From source file:org.gephi.io.importer.plugin.file.spreadsheet.SpreadsheetUtils.java

public static CSVParser configureCSVParser(File file, Character fieldSeparator, Charset charset,
        boolean withFirstRecordAsHeader) throws IOException {
    if (fieldSeparator == null) {
        fieldSeparator = ',';
    }/* w  w w.ja v  a2 s  . co  m*/

    CSVFormat csvFormat = CSVFormat.DEFAULT.withDelimiter(fieldSeparator).withEscape('\\')
            .withIgnoreEmptyLines(true).withNullString("").withIgnoreSurroundingSpaces(true).withTrim(true);

    if (withFirstRecordAsHeader) {
        csvFormat = csvFormat.withFirstRecordAsHeader().withAllowMissingColumnNames(false)
                .withIgnoreHeaderCase(false);
    } else {
        csvFormat = csvFormat.withHeader((String[]) null).withSkipHeaderRecord(false);
    }

    boolean hasBOM = false;
    try (FileInputStream is = new FileInputStream(file)) {
        CharsetToolkit charsetToolkit = new CharsetToolkit(is);
        hasBOM = charsetToolkit.hasUTF8Bom() || charsetToolkit.hasUTF16BEBom()
                || charsetToolkit.hasUTF16LEBom();
    } catch (IOException e) {
        //NOOP
    }

    FileInputStream fileInputStream = new FileInputStream(file);
    InputStreamReader is = new InputStreamReader(fileInputStream, charset);
    if (hasBOM) {
        try {
            is.read();
        } catch (IOException e) {
            // should never happen, as a file with no content
            // but with a BOM has at least one char
        }
    }
    return new CSVParser(is, csvFormat);
}

From source file:cit360.sandbox.BackEndMenu.java

public static final void urltest() {
    URL url;//from  w w w  .  j  a v  a 2s . c o m
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://marvelcomicsuniverse.com");

        urlConnection = (HttpURLConnection) url.openConnection();

        InputStream in = urlConnection.getInputStream();

        InputStreamReader isw = new InputStreamReader(in);

        int data = isw.read();
        while (data != -1) {
            char current = (char) data;
            data = isw.read();
            System.out.print(current);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            urlConnection.disconnect();
        } catch (Exception e) {
            e.printStackTrace(); //If you want further info on failure...
        }
    }
}