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:URLReader.java

public static void main(String[] args) throws Exception {
    URL yahoo = new URL("http://www.yahoo.com/");
    BufferedReader in = new BufferedReader(new InputStreamReader(yahoo.openStream()));

    String inputLine;/*from w w w.j a v  a 2s.  c o m*/

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

    in.close();
}

From source file:com.kasabi.data.movies.freebase.FreebaseMovies2RDF.java

public static void main(String[] args) throws Exception {
    String filename = "/backups/tmp/freebase-datadump-quadruples.tsv.bz2";
    BufferedReader in = new BufferedReader(
            new InputStreamReader(new BZip2CompressorInputStream(new FileInputStream(filename))));
    String line;/* ww  w  .j av a  2s . co  m*/
    int count = 0;

    Model model = MoviesCommon.createModel();
    String prev_subject = null;
    while ((line = in.readLine()) != null) {
        count++;
        String[] tokens = line.split("\\t");

        if (tokens.length > 0) {
            String subject = tokens[0].trim();
            if (!subject.equals(prev_subject)) {
                process(model);
                model = MoviesCommon.createModel();
            }
            prev_subject = subject;
            if ((tokens.length == 3) && (tokens[0].trim().length() > 0) && (tokens[1].trim().length() > 0)
                    && (tokens[2].trim().length() > 0)) {
                output_resource(model, tokens[0], tokens[1], tokens[2]);
            } else if ((tokens.length == 4) && (tokens[0].trim().length() > 0)
                    && (tokens[1].trim().length() > 0) && (tokens[3].trim().length() > 0)) {
                if (tokens[2].trim().length() == 0) {
                    output_literal(model, tokens[0], tokens[1], tokens[3]);
                } else {
                    if (tokens[2].startsWith(LANG)) {
                        output_literal_lang(model, tokens[0], tokens[1], tokens[3], tokens[2]);
                    } else {
                        if (tokens[1].equals("/type/object/key")) {
                            output_literal2(model, tokens[0], tokens[1], tokens[2], tokens[3]);
                        } else if ((tokens[1].equals("/type/object/name"))
                                && (tokens[2].startsWith("/guid/"))) {
                            output_literal2(model, tokens[0], tokens[1], tokens[2], tokens[3]);
                        } else {
                            log.warn("Unexpected data at {}, ignoring: {}", count, line);
                        }
                    }
                }
            } else {
                if (tokens.length < 3) {
                    log.warn("Line {} has only {} tokens: {}", new Object[] { count, tokens.length, line });
                } else {
                    log.warn("Line {} has one or more empty tokens: {}", new Object[] { count, line });
                }
            }

        }
        if (count % 1000000 == 0)
            log.info("Processed {} lines...", count);
    }
}

From source file:Connect.java

public static void main(String[] args) {
    try { // Handle exceptions below
        // Get our command-line arguments
        String hostname = args[0];
        int port = Integer.parseInt(args[1]);
        String message = "";
        if (args.length > 2)
            for (int i = 2; i < args.length; i++)
                message += args[i] + " ";

        // Create a Socket connected to the specified host and port.
        Socket s = new Socket(hostname, port);

        // Get the socket output stream and wrap a PrintWriter around it
        PrintWriter out = new PrintWriter(s.getOutputStream());

        // Sent the specified message through the socket to the server.
        out.print(message + "\r\n");
        out.flush(); // Send it now.

        // Get an input stream from the socket and wrap a BufferedReader
        // around it, so we can read lines of text from the server.
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        // Before we start reading the server's response tell the socket
        // that we don't want to wait more than 3 seconds
        s.setSoTimeout(3000);//w w  w. j  a  va  2  s.  c  o  m

        // Now read lines from the server until the server closes the
        // connection (and we get a null return indicating EOF) or until
        // the server is silent for 3 seconds.
        try {
            String line;
            while ((line = in.readLine()) != null)
                // If we get a line
                System.out.println(line); // print it out.
        } catch (SocketTimeoutException e) {
            // We end up here if readLine() times out.
            System.err.println("Timeout; no response from server.");
        }

        out.close(); // Close the output stream
        in.close(); // Close the input stream
        s.close(); // Close the socket
    } catch (IOException e) { // Handle IO and network exceptions here
        System.err.println(e);
    } catch (NumberFormatException e) { // Bad port number
        System.err.println("You must specify the port as a number");
    } catch (ArrayIndexOutOfBoundsException e) { // wrong # of args
        System.err.println("Usage: Connect <hostname> <port> message...");
    }
}

From source file:NewFingerServer.java

public static void main(String[] arguments) throws Exception {
    ServerSocketChannel sockChannel = ServerSocketChannel.open();
    sockChannel.configureBlocking(false);

    InetSocketAddress server = new InetSocketAddress("localhost", 79);
    ServerSocket socket = sockChannel.socket();
    socket.bind(server);/*  ww  w .j  a v  a 2s.c o m*/

    Selector selector = Selector.open();
    sockChannel.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();
        Set keys = selector.selectedKeys();
        Iterator it = keys.iterator();
        while (it.hasNext()) {
            SelectionKey selKey = (SelectionKey) it.next();
            it.remove();
            if (selKey.isAcceptable()) {
                ServerSocketChannel selChannel = (ServerSocketChannel) selKey.channel();
                ServerSocket selSocket = selChannel.socket();
                Socket connection = selSocket.accept();

                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader is = new BufferedReader(isr);
                PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()), false);
                pw.println("NIO Finger Server");
                pw.flush();
                String outLine = null;
                String inLine = is.readLine();
                if (inLine.length() > 0) {
                    outLine = inLine;
                }
                readPlan(outLine, pw);
                pw.flush();
                pw.close();
                is.close();

                connection.close();
            }
        }
    }
}

From source file:CalcoloRitardiLotti.java

public static void main(String[] args) {
    String id_ref = "cbededce-269f-48d2-8c25-2359bf246f42";
    String requestString = "http://dati.openexpo2015.it/catalog/api/action/datastore_search?resource_id="
            + id_ref;/*from  w  w  w.j  a va 2s .c  o  m*/
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(requestString);
    try {

        HttpResponse response = client.execute(request);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String result = "";
        String resline = "";
        Calendar c = Calendar.getInstance();
        Date current = Date.valueOf(
                c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH));
        while ((resline = rd.readLine()) != null)
            result += resline;

        //System.out.println(jsonObject.toString());
        if (result != null) {
            JSONObject jsonObject = new JSONObject(result);
            JSONObject resultJson = (JSONObject) jsonObject.get("result");
            JSONArray records = (JSONArray) resultJson.get("records");
            Date temp1, temp2;
            //System.out.printf(records.toString());
            long diffInizioFineLavori;
            long ritardo;
            long den = (24 * 60 * 60 * 1000);
            JSONObject temp;

            DefaultCategoryDataset cdata = new DefaultCategoryDataset();
            String partialQuery;
            DefaultPieDataset data = new DefaultPieDataset();

            String totalQuery = "";
            int countSospesi = 0;
            int countConclusi = 0;
            int countVerifica = 0;
            int countInCorso = 0;
            int countCollaudo = 0;
            String stato;
            for (int i = 0; i < records.length(); i++) {
                temp = (JSONObject) records.get(i);
                temp1 = Date.valueOf((temp.getString("Data Consegna Lavori")).substring(0, 10));
                temp2 = Date.valueOf((temp.getString("Data Fine lavori")).substring(0, 10));
                diffInizioFineLavori = (long) (temp2.getTime() - temp1.getTime()) / den;
                stato = temp.getString("STATO");
                if (stato.equals("Concluso"))
                    countConclusi++;
                else if (stato.equals("In corso"))
                    countInCorso++;
                else if (stato.contains("Verifiche"))
                    countVerifica++;
                else if (stato.contains("Collaudo sospeso") || stato.contains("sospeso"))
                    countSospesi++;
                else
                    countCollaudo++;

                if (!temp.getString("STATO").equals("Concluso") && temp2.getTime() < current.getTime())
                    ritardo = (long) (current.getTime() - temp2.getTime()) / den;
                else
                    ritardo = 0;

                cdata.setValue(ritardo, String.valueOf(i + 1), String.valueOf(i + 1));
                System.out.println(
                        "Opera: " + temp.getString("Oggetto del lotto") + " | id: " + temp.getInt("_id"));
                System.out.println("Data consegna lavoro: " + temp.getString("Data Consegna Lavori")
                        + " | Data fine lavoro: " + temp.getString("Data Fine lavori"));
                System.out.println("STATO: " + temp.getString("STATO"));
                System.out.println("Differenza in giorni: " + diffInizioFineLavori
                        + " | Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali"));
                System.out.println("Ritardo accumulato: " + ritardo);

                System.out.println("----------------------------------");

                partialQuery = "\nid: " + temp.getInt("_id") + "\nOpera:" + temp.getString("Oggetto del lotto")
                        + "\n" + "Data consegna lavoro: " + temp.getString("Data Consegna Lavori")
                        + "Data fine lavoro: " + temp.getString("Data Fine lavori") + "\n" + "STATO: "
                        + temp.getString("STATO") + "\n" + "Differenza in giorni: " + diffInizioFineLavori
                        + " - Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali")
                        + "\n" + "Ritardo accumulato: " + ritardo + "\n"
                        + "----------------------------------\n";
                totalQuery = totalQuery + partialQuery;

            }

            JFreeChart chart1 = ChartFactory.createBarChart3D("RITARDI AL " + current, "Id lotto",
                    "ritardo(in giorni)", cdata);
            ChartRenderingInfo info = null;
            ChartUtilities.saveChartAsPNG(
                    new File(System.getProperty("user.dir") + "/istogramma" + current + ".png"), chart1, 1500,
                    1500, info, true, 10);
            FileUtils.writeStringToFile(new File(current + "_1.txt"), totalQuery);

            data.setValue("Conclusi: " + countConclusi, countConclusi);
            data.setValue("Sospeso: " + countSospesi, countSospesi);
            data.setValue("In Corso: " + countInCorso, countInCorso);
            data.setValue("Verifica: " + countVerifica, countVerifica);
            data.setValue("Collaudo: " + countCollaudo, countCollaudo);
            JFreeChart chart2 = ChartFactory.createPieChart3D("Statistiche del " + current, data, true, true,
                    true);
            ChartUtilities.saveChartAsPNG(new File(System.getProperty("user.dir") + "/pie" + current + ".png"),
                    chart2, 800, 450);

        }

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

From source file:com.estafeta.flujos.DemoMain.java

/**
 * Clase principal del proyecto//  ww  w . j  a va  2  s . co  m
 * @param args argumentos de linea de comandos
 */
public static void main(String[] args) {
    // init spring context
    ApplicationContext ctx = new ClassPathXmlApplicationContext(APPLOCATION_CONTEXT_FILE);
    // get bean from context
    JmsMessageSender jmsMessageSender = (JmsMessageSender) ctx.getBean(JMS_MESSAGE_SENDER_BEAN_NAME);
    // send to a code specified destination
    Queue queue = new ActiveMQQueue(JMS_DESTINATION_NAME);
    try {
        ClassLoader classLoader = DemoMain.class.getClassLoader();
        FileInputStream fileInputStream = new FileInputStream(
                classLoader.getResource(MOCK_INPUT_FILE).getFile());
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(fileInputStream, Charset.forName(UTF_8_CHARSET)));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            jmsMessageSender.send(queue, line);
        }
        fileInputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    // close spring application context
    ((ClassPathXmlApplicationContext) ctx).close();
}

From source file:de.zib.vold.userInterface.ABI.java

public static void main(String[] args) {
    ABI abi = new ABI();

    while (true) {
        try {//from  w  w  w  .j a v a 2s .c o m
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);

            System.out.print("#: ");

            String s = br.readLine();
            if (null == s)
                break;

            String[] a = s.split("\\s+");

            if (a.length < 1) {
                System.out.println("ERROR: The following commands are valid:");
                System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*");
                System.out.println("ERROR: lookup <scope> <type> <keyname>");
                System.out.println("ERROR: exit");

                continue;
            } else if (a[0].equals("lookup") || a[0].equals("l")) {
                if (a.length < 4) {
                    System.out.println("ERROR: Syntax for lookup is:");
                    System.out.println("ERROR: lookup <scope> <type> <keyname>");

                    continue;
                }

                Map<Key, Set<String>> result;
                try {
                    result = abi.frontend.lookup(new Key(a[1], a[2], a[3]));
                } catch (VoldException e) {
                    System.out.println(
                            "An internal error occured: " + e.getClass().getName() + ": " + e.getMessage());
                    continue;
                }

                for (Map.Entry<Key, Set<String>> entry : result.entrySet()) {
                    Key k = entry.getKey();
                    System.out.println("+Found ('" + k.get_scope() + "', '" + k.get_type() + "', '"
                            + k.get_keyname() + "')");

                    for (String v : entry.getValue()) {
                        System.out.println("-" + v);
                    }
                }
            } else if (a[0].equals("insert") || a[0].equals("i")) {
                if (a.length < 5) {
                    System.out.println("ERROR: Syntax for insert is:");
                    System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*");

                    continue;
                }

                Key k = new Key(a[2], a[3], a[4]);

                Set<String> values = new HashSet<String>();
                for (int i = 5; i < a.length; ++i) {
                    values.add(a[i]);
                }

                try {
                    abi.frontend.insert(a[1], k, values, DateTime.now().getMillis());
                } catch (VoldException e) {
                    System.out.println(
                            "An internal error occured: " + e.getClass().getName() + ": " + e.getMessage());
                    continue;
                }
            } else if (a[0].equals("exit") || a[0].equals("x")) {
                break;
            } else {
                System.out.println("ERROR: Unknown command!");
                System.out.println("ERROR: The following commands are valid:");
                System.out.println("ERROR: insert <source> <scope> <type> <keyname> {<value> }*");
                System.out.println("ERROR: lookup <scope> <type> <keyname>");
                System.out.println("ERROR: exit");
            }

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

    System.exit(0);
}

From source file:com.sankalp.characterreader.CharacterReader.java

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

    double learningRate = 0.55;
    List<NeuralNetwork.Layer> hiddenLayerList = new ArrayList();
    hiddenLayerList.add(new NeuralNetwork.Layer(50));
    NeuralNetwork neuralNetwork = new NeuralNetwork(new NeuralNetwork.Layer(28 * 28),
            new NeuralNetwork.Layer(10), hiddenLayerList, learningRate);

    int trainingSampleCount = 60000;
    TrainingData trainingData = new TrainingData(new File("/home/sankalpkulshrestha/mnist/train-images/"),
            trainingSampleCount, new File("/home/sankalpkulshrestha/mnist/train-labels.csv"));

    int totalEpochs = 30;
    for (int index = 0; index < totalEpochs; index++) {
        System.out.println("---------- EPOCH " + index + " ----------");
        neuralNetwork.train(trainingData);

        TrainingData testData = new TrainingData(new File("/home/sankalpkulshrestha/mnist/test-images/"), 10000,
                new File("/home/sankalpkulshrestha/mnist/test-labels.csv"));

        System.out.println("Training over");
        double accuracy = neuralNetwork.measureAccuracy(testData);
        System.out.println(accuracy);
        if (index < totalEpochs - 1) {
            trainingData.shuffle();// www .  ja  va  2  s  . com
            trainingData.reset();
        }
    }
    System.out.println("Model trained. Enter image file names:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int number = -1;
    List<String> expectedOutputList = FileUtils
            .readLines(new File("/home/sankalpkulshrestha/mnist/test-labels.csv"), "UTF-8");
    while ((number = Integer.parseInt(br.readLine())) != -1) {
        int output = neuralNetwork.test(new TrainingData.Sample(
                new File("/home/sankalpkulshrestha/mnist/test-images/" + number + ".jpg"), 0));
        System.out.println(output);
    }
}

From source file:jmxbf.java

public static void main(String[] args) throws IOException, MalformedObjectNameException {

    String HOST = "";
    String PORT = "";
    String usersFile = "";
    String pwdFile = "";

    CommandLine cmd = getParsedCommandLine(args);

    if (cmd != null) {

        HOST = cmd.getOptionValue("host");
        PORT = cmd.getOptionValue("port");
        usersFile = cmd.getOptionValue("usernames-file");
        pwdFile = cmd.getOptionValue("passwords-file");

    } else {/*from  w  ww . j a va2  s .co m*/

        System.exit(1);
    }

    String finalResults = "";

    BufferedReader users = new BufferedReader(new FileReader(usersFile));
    BufferedReader pwds = new BufferedReader(new FileReader(pwdFile));

    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + HOST + ":" + PORT + "/jmxrmi");
    //new JMXServiceURL("service:jmx:remoting-jmx://" + HOST + ":" + PORT);

    String user = null;
    boolean found = false;
    while ((user = users.readLine()) != null) {
        String pwd = null;
        while ((pwd = pwds.readLine()) != null) {
            //System.out.println(user+":"+pwd);

            Map<String, String[]> env = new HashMap<>();
            String[] credentials = { user, pwd };
            env.put(JMXConnector.CREDENTIALS, credentials);
            try {

                JMXConnector jmxConnector = JMXConnectorFactory.connect(url, env);

                System.out.println();
                System.out.println();
                System.out.println();
                System.out.println(
                        "[+] ###SUCCESS### - We got a valid connection for: " + user + ":" + pwd + "\r\n\r\n");
                finalResults = finalResults + "\n" + user + ":" + pwd;
                jmxConnector.close();
                found = true;
                break;

            } catch (java.lang.SecurityException e) {
                System.out.println("Auth failed!!!\r\n");

            }
        }
        if (found) {
            System.out.println("Found some valid credentials - continuing brute force");
            found = false;

        }
        //closing and reopening pwds
        pwds.close();
        pwds = new BufferedReader(new FileReader(pwdFile));

    }

    users.close();
    //print final results
    if (finalResults.length() != 0) {
        System.out.println("The following valid credentials were found:\n");
        System.out.println(finalResults);
    }

}

From source file:examples.nntp.post.java

public final static void main(String[] args) {
    String from, subject, newsgroup, filename, server, organization;
    String references;/*from  w w w .j ava 2 s.  c o  m*/
    BufferedReader stdin;
    FileReader fileReader = null;
    SimpleNNTPHeader header;
    NNTPClient client;

    if (args.length < 1) {
        System.err.println("Usage: post newsserver");
        System.exit(1);
    }

    server = args[0];

    stdin = new BufferedReader(new InputStreamReader(System.in));

    try {
        System.out.print("From: ");
        System.out.flush();

        from = stdin.readLine();

        System.out.print("Subject: ");
        System.out.flush();

        subject = stdin.readLine();

        header = new SimpleNNTPHeader(from, subject);

        System.out.print("Newsgroup: ");
        System.out.flush();

        newsgroup = stdin.readLine();
        header.addNewsgroup(newsgroup);

        while (true) {
            System.out.print("Additional Newsgroup <Hit enter to end>: ");
            System.out.flush();

            // Of course you don't want to do this because readLine() may be null
            newsgroup = stdin.readLine().trim();

            if (newsgroup.length() == 0)
                break;

            header.addNewsgroup(newsgroup);
        }

        System.out.print("Organization: ");
        System.out.flush();

        organization = stdin.readLine();

        System.out.print("References: ");
        System.out.flush();

        references = stdin.readLine();

        if (organization != null && organization.length() > 0)
            header.addHeaderField("Organization", organization);

        if (references != null && organization.length() > 0)
            header.addHeaderField("References", references);

        header.addHeaderField("X-Newsreader", "NetComponents");

        System.out.print("Filename: ");
        System.out.flush();

        filename = stdin.readLine();

        try {
            fileReader = new FileReader(filename);
        } catch (FileNotFoundException e) {
            System.err.println("File not found. " + e.getMessage());
            System.exit(1);
        }

        client = new NNTPClient();
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

        client.connect(server);

        if (!NNTPReply.isPositiveCompletion(client.getReplyCode())) {
            client.disconnect();
            System.err.println("NNTP server refused connection.");
            System.exit(1);
        }

        if (client.isAllowedToPost()) {
            Writer writer = client.postArticle();

            if (writer != null) {
                writer.write(header.toString());
                Util.copyReader(fileReader, writer);
                writer.close();
                client.completePendingCommand();
            }
        }

        fileReader.close();

        client.logout();

        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}