Example usage for java.io BufferedReader BufferedReader

List of usage examples for java.io BufferedReader BufferedReader

Introduction

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

Prototype

public BufferedReader(Reader in) 

Source Link

Document

Creates a buffering character-input stream that uses a default-sized input buffer.

Usage

From source file:Grep1.java

/** Main will make a Grep object for the pattern, and run it
 * on all input files listed in argv./*w  w w  .ja  v a 2s .c  om*/
 */
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:ProcessorDemo.java

public static void main(String args[]) {
    try {//from  w  w w  .j  a  v  a 2 s .c  o  m
        System.setProperty("sen.home", "../Sen1221/senhome-ipadic");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "FATAL");

        if (args.length != 2) {
            System.err.println("usage: java ProcessorDemo <filename> <encoding>");
            System.exit(1);
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), args[1]));
        String confPath = System.getProperty("sen.home") + System.getProperty("file.separator")
                + "conf/sen-processor.xml";
        StreamTagger tagger = new StreamTagger((Reader) br, confPath);
        readConfig(confPath);

        if (!isCompound) {
            CompoundWordPostProcessor cwProcessor = new CompoundWordPostProcessor(compoundFile);
            tagger.addPostProcessor(cwProcessor);
        }

        if (compositRule != null && !compositRule.equals("")) {
            CompositPostProcessor processor = new CompositPostProcessor();
            processor.readRules(new BufferedReader(new StringReader(compositRule)));
            tagger.addPostProcessor(processor);
        }

        if (remarkRule != null && !remarkRule.equals("")) {
            RemarkPreProcessor processor = new RemarkPreProcessor();
            processor.readRules(new BufferedReader(new StringReader(remarkRule)));
            tagger.addPreProcessor(processor);
            RemarkPostProcessor p2 = new RemarkPostProcessor();
            tagger.addPostProcessor(p2);
        }

        // BufferedReader is = new BufferedReader(System.in);

        while (tagger.hasNext()) {
            Token token = tagger.next();
            System.out.println(token.getSurface() + "\t" + token.getPos() + "\t" + token.start() + "\t"
                    + token.end() + "\t" + token.getCost() + "\t" + token.getAddInfo());
        }

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

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   www.ja  v a2 s .c o 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;// www .  j  a va 2 s  . c  om

    // 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//  w  w w  . ja va2  s  . 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);
        }
    }
}

From source file:org.wso2.charon3.samples.group.sample01.CreateGroupSample.java

public static void main(String[] args) {
    try {/*from   w  ww .  j a  v  a  2s  .  c o m*/
        String url = "http://localhost:8080/scim/v2/Groups";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // Setting basic post request
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/scim+json");

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(createRequestBody);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();

        BufferedReader in;
        if (responseCode == HttpURLConnection.HTTP_CREATED) { // success
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        } else {
            in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        }
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //printing result from response
        System.out.println("Response Code : " + responseCode);
        System.out.println("Response Message : " + con.getResponseMessage());
        System.out.println("Response Content : " + response.toString());

    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:info.bitoo.Daemon.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//from w w  w.  j av a  2  s  .  c  o  m
    try {
        cmd = parser.parse(createCommandLineOptions(), args);
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
    }

    Properties props = Main.readConfiguration(cmd);

    BufferedReader input = new BufferedReader(new FileReader(cmd.getOptionValue("p")));

    Daemon daemon = new Daemon(props, input);
    daemon.deamonMain();
}

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 w  w w . j a va  2 s.c  o m
    // 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:com.linkedin.pinotdruidbenchmark.PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    if (args.length != 3 && args.length != 4) {
        System.err.println(//from ww  w .j  a  v a 2s . c  om
                "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    final int numClients = Integer.parseInt(args[2]);
    final long endTime;
    if (args.length == 3) {
        endTime = Long.MAX_VALUE;
    } else {
        endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND;
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    final int numQueries = queryFiles.length;
    final HttpPost[] httpPosts = new HttpPost[numQueries];
    for (int i = 0; i < numQueries; i++) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        String query = new BufferedReader(new FileReader(queryFiles[i])).readLine();
        httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
        httpPosts[i] = httpPost;
    }

    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(numClients);

    for (int i = 0; i < numClients; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    while (System.currentTimeMillis() < endTime) {
                        long startTime = System.currentTimeMillis();
                        CloseableHttpResponse httpResponse = httpClient
                                .execute(httpPosts[RANDOM.nextInt(numQueries)]);
                        httpResponse.close();
                        long responseTime = System.currentTimeMillis() - startTime;
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(responseTime);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executorService.shutdown();

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < endTime) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:com.iveely.computing.Program.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException/*from  www . j  av  a  2s. c o m*/
 */
public static void main(String[] args) throws IOException {
    if (args != null && args.length > 0) {
        logger.info("start computing with arguments:" + String.join(",", args));
        String type = args[0].toLowerCase(Locale.CHINESE);
        switch (type) {
        case "master":
            launchMaster();
            return;
        case "slave":
            if (args.length == 4) {
                ConfigWrapper.get().getSlave().setPort(Integer.parseInt(args[1]));
                ConfigWrapper.get().getSlave().setSlot(Integer.parseInt(args[2]));
                ConfigWrapper.get().getSlave().setSlotCount(Integer.parseInt(args[3]));
            }
            launchSlave();
            return;
        case "supervisor":
            launchSupervisor();
            return;
        case "console":
            launchConsole();
            return;
        }
    }
    logger.error("arguments error,example [master | supervisor | slave | console]");
    System.out.println("press any keys to exit...");
    new BufferedReader(new InputStreamReader(System.in)).readLine();
}