Example usage for java.io InputStreamReader InputStreamReader

List of usage examples for java.io InputStreamReader InputStreamReader

Introduction

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

Prototype

public InputStreamReader(InputStream in) 

Source Link

Document

Creates an InputStreamReader that uses the default charset.

Usage

From source file:com.trendmicro.hdfs.webdav.tool.Get.java

public static void main(String[] args) throws Exception {
    // Process command line 

    Options options = new Options();
    options.addOption("d", "debug", false, "Enable debug logging");

    CommandLine cmd = null;//from w ww  .  j a va2s  .c o  m
    try {
        cmd = new PosixParser().parse(options, args);
    } catch (ParseException e) {
        printUsageAndExit(options, -1);
    }
    boolean debug = cmd.hasOption('d');
    args = cmd.getArgs();
    if (args.length < 1) {
        printUsageAndExit(options, -1);
    }

    // Do the fetch

    AuthenticatedURL.Token token = new AuthenticatedURL.Token();
    AuthenticatedURL url = new AuthenticatedURL();
    HttpURLConnection conn = url.openConnection(new URL(args[0]), token);
    if (debug) {
        System.out.println("Token value: " + token);
        System.out.println("Status code: " + conn.getResponseCode() + " " + conn.getResponseMessage());
    }
    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
        reader.close();
    }
    System.out.println();
}

From source file:com.asual.lesscss.LessEngineCli.java

public static void main(String[] args) throws LessException, URISyntaxException {
    Options cmdOptions = new Options();
    cmdOptions.addOption(LessOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8.");
    cmdOptions.addOption(LessOptions.COMPRESS_OPTION, false, "Flag that enables compressed CSS output.");
    cmdOptions.addOption(LessOptions.CSS_OPTION, false, "Flag that enables compilation of .css files.");
    cmdOptions.addOption(LessOptions.LESS_OPTION, true, "Path to a custom less.js for Rhino version.");
    try {/*from  w  w  w. j  a  v  a2  s. c o m*/
        CommandLineParser cmdParser = new GnuParser();
        CommandLine cmdLine = cmdParser.parse(cmdOptions, args);
        LessOptions options = new LessOptions();
        if (cmdLine.hasOption(LessOptions.CHARSET_OPTION)) {
            options.setCharset(cmdLine.getOptionValue(LessOptions.CHARSET_OPTION));
        }
        if (cmdLine.hasOption(LessOptions.COMPRESS_OPTION)) {
            options.setCompress(true);
        }
        if (cmdLine.hasOption(LessOptions.CSS_OPTION)) {
            options.setCss(true);
        }
        if (cmdLine.hasOption(LessOptions.LESS_OPTION)) {
            options.setLess(new File(cmdLine.getOptionValue(LessOptions.LESS_OPTION)).toURI().toURL());
        }
        LessEngine engine = new LessEngine(options);
        if (System.in.available() != 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringWriter sw = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = in.read(buffer))) {
                sw.write(buffer, 0, n);
            }
            String src = sw.toString();
            if (!src.isEmpty()) {
                System.out.println(engine.compile(src, null, options.isCompress()));
                System.exit(0);
            }
        }
        String[] files = cmdLine.getArgs();
        if (files.length == 1) {
            System.out.println(engine.compile(new File(files[0]), options.isCompress()));
            System.exit(0);
        }
        if (files.length == 2) {
            engine.compile(new File(files[0]), new File(files[1]), options.isCompress());
            System.exit(0);
        }

    } catch (IOException ioe) {
        System.err.println("Error opening input file.");
    } catch (ParseException pe) {
        System.err.println("Error parsing arguments.");
    }
    String[] paths = LessEngine.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()
            .split(File.separator);
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("java -jar " + paths[paths.length - 1] + " input [output] [options]", cmdOptions);
    System.exit(1);
}

From source file:Reverse.java

public static void main(String[] args) throws Exception {

    if (args.length != 1) {
        System.err.println("Usage:  java Reverse " + "string_to_reverse");
        System.exit(1);//from  w w w . j av a 2 s .  c  o  m
    }

    String stringToReverse = URLEncoder.encode(args[0]);

    URL url = new URL("http://java.sun.com/cgi-bin/backwards");
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());
    out.println("string=" + stringToReverse);
    out.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

    in.close();
}

From source file:edu.cmu.lti.oaqa.bio.index.medline.annotated.query.SimpleQueryApp.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("u", null, true, "Solr URI");
    options.addOption("n", null, true, "Max # of results");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {//from   w w w.j  a  va2 s  .  c  o  m
        CommandLine cmd = parser.parse(options, args);
        String solrURI = null;

        solrURI = cmd.getOptionValue("u");
        if (solrURI == null) {
            Usage("Specify Solr URI");
        }

        SolrServerWrapper solr = new SolrServerWrapper(solrURI);

        int numRet = 10;

        if (cmd.hasOption("n")) {
            numRet = Integer.parseInt(cmd.getOptionValue("n"));
        }

        List<String> fieldList = new ArrayList<String>();
        fieldList.add(UtilConstMedline.ID_FIELD);
        fieldList.add(UtilConstMedline.SCORE_FIELD);
        fieldList.add(UtilConstMedline.ARTICLE_TITLE_FIELD);
        fieldList.add(UtilConstMedline.ENTITIES_DESC_FIELD);
        fieldList.add(UtilConstMedline.ABSTRACT_TEXT_FIELD);

        BufferedReader sysInReader = new BufferedReader(new InputStreamReader(System.in));
        Joiner commaJoiner = Joiner.on(',');

        while (true) {
            System.out.println("Input query: ");
            String query = sysInReader.readLine();
            if (null == query)
                break;

            QueryTransformer qt = new QueryTransformer(query);

            String tranQuery = qt.getQuery();

            System.out.println("Translated query:");
            System.out.println(tranQuery);
            System.out.println("=========================");

            SolrDocumentList res = solr.runQuery(tranQuery, fieldList, numRet);

            System.out.println("Found " + res.getNumFound() + " entries");

            for (SolrDocument doc : res) {
                String id = (String) doc.getFieldValue(UtilConstMedline.ID_FIELD);
                float score = (Float) doc.getFieldValue(UtilConstMedline.SCORE_FIELD);
                String title = (String) doc.getFieldValue(UtilConstMedline.ARTICLE_TITLE_FIELD);
                String titleAbstract = (String) doc.getFieldValue(UtilConstMedline.ABSTRACT_TEXT_FIELD);

                System.out.println(score + " PMID=" + id + " " + titleAbstract);

                String entityDesc = (String) doc.getFieldValue(UtilConstMedline.ENTITIES_DESC_FIELD);
                System.out.println("Entities:");
                for (EntityEntry e : EntityEntry.parseEntityDesc(entityDesc)) {
                    System.out.println(String.format("[%d %d] concept=%s concept_ids=%s", e.mStart, e.mEnd,
                            e.mConcept, commaJoiner.join(e.mConceptIds)));
                }
            }
        }

        solr.close();

    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:ReadGZIP.java

public static void main(String[] argv) throws IOException {
    String FILENAME = "file.txt.gz";

    // Since there are 4 constructor calls here, I wrote them out in full.
    // In real life you would probably nest these constructor calls.
    FileInputStream fin = new FileInputStream(FILENAME);
    GZIPInputStream gzis = new GZIPInputStream(fin);
    InputStreamReader xover = new InputStreamReader(gzis);
    BufferedReader is = new BufferedReader(xover);

    String line;//from   www  . j ava 2s . com
    // Now read lines of text: the BufferedReader puts them in lines,
    // the InputStreamReader does Unicode conversion, and the
    // GZipInputStream "gunzip"s the data from the FileInputStream.
    while ((line = is.readLine()) != null)
        System.out.println("Read: " + line);
}

From source file:org.salever.rcp.remoteSystem.server.util.ClientAbortMethod.java

public final static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    try {//from w  ww.  j  ava  2 s.  c  o  m

        String queryString = "wd=?ddd=";
        String decodeUrl = URLEncoder.encode(queryString, "GBK");
        String string = new String(decodeUrl);
        System.out.println("--------------" + string + "--------------------------");
        HttpGet httpget = new HttpGet("http://www.baidu.com/s?" + string);

        System.out.println("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line;
            while ((line = reader.readLine()) != null) {
                // System.out.println(line);
            }
        }
        System.out.println("----------------------------------------");

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:Grep1.java

/** Main will make a Grep object for the pattern, and run it
 * on all input files listed in argv.//from w w w .  j a v  a 2s .co m
 */
public static void main(String[] argv) throws Exception {

    if (argv.length < 1) {
        System.err.println("Usage: Grep1 pattern [filename]");
        System.exit(1);
    }

    Grep1 pg = new Grep1(argv[0]);

    if (argv.length == 1)
        pg.process(new BufferedReader(new InputStreamReader(System.in)), "(standard input)", false);
    else
        for (int i = 1; i < argv.length; i++) {
            pg.process(new BufferedReader(new FileReader(argv[i])), argv[i], true);
        }
}

From source file:msgsend.java

public static void main(String[] argv) {
    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//from   w  ww  .j  a va2s .co  m
    String mailer = "msgsend";
    String file = null;
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    /*
     * Process command line arguments.
     */
    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-a")) {
            file = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-a attach-file] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        /*
         * Prompt for To and Subject, if not specified.
         */
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        /*
         * Initialize the JavaMail Session.
         */
        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        /*
         * Construct the message and send it.
         */
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        String text = collect(in);

        if (file != null) {
            // Attach the specified file.
            // We need a multipart message to hold the attachment.
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(text);
            MimeBodyPart mbp2 = new MimeBodyPart();
            mbp2.attachFile(file);
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);
            msg.setContent(mp);
        } else {
            // If the desired charset is known, you can use
            // setText(text, charset)
            msg.setText(text);
        }

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        /*
         * Save a copy of the message, if requested.
         */
        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();

                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }

            // Get record Folder.  Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ExecDemoSort.java

public static void main(String[] av) throws IOException {

    // A Runtime object has methods for dealing with the OS
    Runtime r = Runtime.getRuntime();

    // A process object tracks one external running process
    Process p;//  w  w w. j  a v a2  s . c  o m

    // file contains unsorted data
    p = r.exec("sort sortdemo.txt");

    // getInputStream gives an Input stream connected to
    // the process p's standard output (and vice versa). We use
    // that to construct a BufferedReader so we can readLine() it.
    BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream()));

    System.out.println("Here is your sorted data:");

    String aLine;
    while ((aLine = is.readLine()) != null)
        System.out.println(aLine);

    System.out.println("That is all, folks!");

    return;
}

From source file:enrichment.Disambiguate.java

/**prerequisites:
 * cd silk_2.5.3/*_links//from  ww  w . jav  a 2s.c o m
 * cat *.nt|sort  -t' ' -k3   > $filename
 * 
 * @param args $filename
 * @throws IOException
 * @throws URISyntaxException
 */
public static void main(String[] args) {
    File file = new File(args[0]);
    if (file.isDirectory()) {
        args = file.list(new OnlyExtFilenameFilter("nt"));
    }

    BufferedReader in;
    for (int q = 0; q < args.length; q++) {
        String filename = null;
        if (file.isDirectory()) {
            filename = file.getPath() + File.separator + args[q];
        } else {
            filename = args[q];
        }
        try {
            FileWriter output = new FileWriter(filename + "_disambiguated.nt");
            String prefix = "@prefix rdrel: <http://rdvocab.info/RDARelationshipsWEMI/> .\n"
                    + "@prefix dbpedia:    <http://de.dbpedia.org/resource/> .\n"
                    + "@prefix frbr:   <http://purl.org/vocab/frbr/core#> .\n"
                    + "@prefix lobid: <http://lobid.org/resource/> .\n"
                    + "@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n"
                    + "@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n"
                    + "@prefix mo: <http://purl.org/ontology/mo/> .\n"
                    + "@prefix wikipedia: <https://de.wikipedia.org/wiki/> .";
            output.append(prefix + "\n\n");
            in = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));

            HashMap<String, HashMap<String, ArrayList<String>>> hm = new HashMap<String, HashMap<String, ArrayList<String>>>();
            String s;
            HashMap<String, ArrayList<String>> hmLobid = new HashMap<String, ArrayList<String>>();
            Stack<String> old_object = new Stack<String>();

            while ((s = in.readLine()) != null) {
                String[] triples = s.split(" ");
                String object = triples[2].substring(1, triples[2].length() - 1);
                if (old_object.size() > 0 && !old_object.firstElement().equals(object)) {
                    hmLobid = new HashMap<String, ArrayList<String>>();
                    old_object = new Stack<String>();
                }
                old_object.push(object);
                String subject = triples[0].substring(1, triples[0].length() - 1);
                System.out.print("\nSubject=" + object);
                System.out.print("\ntriples[2]=" + triples[2]);
                hmLobid.put(subject, getAllCreators(new URI(subject)));
                hm.put(object, hmLobid);

            }
            // get all dbpedia resources
            for (String key_one : hm.keySet()) {
                System.out.print("\n==============\n==== " + key_one + "\n===============");
                int resources_cnt = hm.get(key_one).keySet().size();
                ArrayList<String>[] creators = new ArrayList[resources_cnt];
                HashMap<String, Integer> creators_backed = new HashMap<String, Integer>();
                int x = 0;
                // get all lobid_resources subsumed under the dbpedia resource
                for (String subject_uri : hm.get(key_one).keySet()) {
                    creators[x] = new ArrayList<String>();
                    System.out.print("\n     subject_uri=" + subject_uri);
                    Iterator<String> ite = hm.get(key_one).get(subject_uri).iterator();
                    int y = 0;
                    // get all creators of the lobid resource
                    while (ite.hasNext()) {
                        String creator = ite.next();
                        System.out.print("\n          " + creator);
                        if (creators_backed.containsKey(creator)) {
                            y = creators_backed.get(creator);
                        } else {
                            y = creators_backed.size();
                            creators_backed.put(creator, y);
                        }
                        while (creators[x].size() <= y) {
                            creators[x].add("-");
                        }
                        creators[x].set(y, creator);
                        y++;
                    }
                    x++;
                }
                if (creators_backed.size() == 1) {
                    System.out
                            .println("\n" + "Every resource pointing to " + key_one + " has the same creator!");
                    for (String key_two : hm.get(key_one).keySet()) {
                        output.append("<" + key_two + "> rdrel:workManifested <" + key_one + "> .\n");
                        output.append("<" + key_two + ">  mo:wikipedia <"
                                + key_one.replaceAll("dbpedia\\.org/resource", "wikipedia\\.org/wiki")
                                + "> .\n");
                    }
                } /*else  {
                    for (int a = 0; a < creators.length; a++) {
                       System.out.print(creators[a].toString()+",");
                    }
                  }*/
            }

            output.flush();
            if (output != null) {
                output.close();
            }
        } catch (Exception e) {
            System.out.print("Exception while working on " + filename + ": \n");
            e.printStackTrace(System.out);
        }
    }
}