Example usage for java.io BufferedReader readLine

List of usage examples for java.io BufferedReader readLine

Introduction

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

Prototype

public String readLine() throws IOException 

Source Link

Document

Reads a line of text.

Usage

From source file:com.leixl.easyframework.action.httpclient.TestHttpPost.java

public static void main(String[] args) {

    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("uid", 1);
    paramMap.put("desc",
            "?????");
    paramMap.put("payStatus", 1);

    //HttpConnUtils.postHttpContent(URL, paramMap);

    //HttpClient//w w w .ja  va  2s .c o m
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(URL);
    // ??
    NameValuePair[] data = { new NameValuePair("uid", "1"),
            new NameValuePair("desc",
                    "?????"),
            new NameValuePair("payStatus", "1") };
    // ?postMethod
    postMethod.setRequestBody(data);
    // postMethod
    int statusCode;
    try {
        statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_OK) {
            StringBuffer contentBuffer = new StringBuffer();
            InputStream in = postMethod.getResponseBodyAsStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in, postMethod.getResponseCharSet()));
            String inputLine = null;
            while ((inputLine = reader.readLine()) != null) {
                contentBuffer.append(inputLine);
                System.out.println("input line:" + inputLine);
                contentBuffer.append("/n");
            }
            in.close();

        } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            // ???
            Header locationHeader = postMethod.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                System.out.println("The page was redirected to:" + location);
            } else {
                System.err.println("Location field value is null.");
            }
        }
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:FlightInfo.java

public static void main(String args[]) {

    String to, from;//from  w  w  w. j  av a  2  s .c  o  m
    Hill ob = new Hill();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    ob.setup();

    try {
        System.out.print("From? ");
        from = br.readLine();
        System.out.print("To? ");
        to = br.readLine();

        ob.isflight(from, to);

        if (ob.btStack.size() != 0)
            ob.route(to);

    } catch (IOException exc) {
        System.out.println("Error on input.");
    }
}

From source file:listfiles.ListFiles.java

/**
 * @param args the command line arguments
 *///w ww. ja  v a 2s  . co  m
public static void main(String[] args) {
    // TODO code application logic here
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String folderPath = "";
    String fileName = "DirectoryFiles.xlsx";

    try {
        System.out.println("Folder path :");
        folderPath = reader.readLine();
        //System.out.println("Output File Name :");
        //fileName = reader.readLine();

        XSSFWorkbook wb = new XSSFWorkbook();
        FileOutputStream fileOut = new FileOutputStream(folderPath + "\\" + fileName);
        XSSFSheet sheet1 = wb.createSheet("Files");
        int row = 0;
        Stream<Path> stream = Files.walk(Paths.get(folderPath));
        Iterator<Path> pathIt = stream.iterator();
        String ext = "";

        while (pathIt.hasNext()) {
            Path filePath = pathIt.next();
            Cell cell1 = checkRowCellExists(sheet1, row, 0);
            Cell cell2 = checkRowCellExists(sheet1, row, 1);
            row++;
            ext = FilenameUtils.getExtension(filePath.getFileName().toString());
            cell1.setCellValue(filePath.getFileName().toString());
            cell2.setCellValue(ext);

        }
        sheet1.autoSizeColumn(0);
        sheet1.autoSizeColumn(1);

        wb.write(fileOut);
        fileOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Program Finished");
}

From source file:com.quix.aia.cn.imo.mapper.UrlForUserData.java

public static void main(String[] args) {
    // TODO Auto-generated method stub
    UserAuthResponds userAuth = new UserAuthResponds();
    try {/*  w ww  . ja va 2  s  . c  o  m*/

        GsonBuilder builder = new GsonBuilder();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String username = "", psw = "", co = "";
        username = "NSNP306";
        psw = "A111111A";
        co = "0986";

        HttpGet getRequest = new HttpGet("http://211.144.219.243/isp/rest/index.do?isAjax=true&account="
                + username + "&co=" + co + "&password=" + psw + "");
        getRequest.addHeader("accept", "application/json");
        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            Gson googleJson = new Gson();
            userAuth = googleJson.fromJson(output, UserAuthResponds.class);
            System.out.println("Success " + userAuth.getSuccess());
            if (userAuth.getSuccess().equals("1")) {
                System.out.println("Login successfully Done");
            } else {

                System.out.println("Login Failed ");
            }

        }
        httpClient.getConnectionManager().shutdown();

        //           googleJson = builder.create();
        //           Type listType = new TypeToken<List<UserAuthResponds>>() {}.getType();

    } catch (ClientProtocolException e) {
        log.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        log.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    }

}

From source file:CopyLines.java

public static void main(String[] args) throws IOException {
    BufferedReader inputStream = null;
    PrintWriter outputStream = null;

    try {/*from  ww w  .jav  a  2  s.co m*/
        inputStream = new BufferedReader(new FileReader("xanadu.txt"));
        outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));

        String l;
        while ((l = inputStream.readLine()) != null) {
            outputStream.println(l);
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:SequentialPersonalizedPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(//from  ww  w.j a  v a 2s  . c o  m
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));
    options.addOption(OptionBuilder.withArgName("node").hasArg()
            .withDescription("source node (i.e., destination of the random jump)").create(SOURCE));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    final String source = cmdline.getOptionValue(SOURCE);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    if (!graph.containsVertex(source)) {
        System.err.println("Error: source node not found in the graph!");
        System.exit(-1);
    }

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute personalized PageRank.
    PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph,
            new Transformer<String, Double>() {
                @Override
                public Double transform(String vertex) {
                    return vertex.equals(source) ? 1.0 : 0;
                }
            }, alpha);

    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:FactQuoter.java

public static void main(String[] args) throws IOException {
    // This is how we set things up to read lines of text from the user.
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    // Loop forever
    for (;;) {/*from ww w  . jav a  2s  .c  o m*/
        // Display a prompt to the user
        System.out.print("FactQuoter> ");
        // Read a line from the user
        String line = in.readLine();
        // If we reach the end-of-file,
        // or if the user types "quit", then quit
        if ((line == null) || line.equals("quit"))
            break;
        // Try to parse the line, and compute and print the factorial
        try {
            int x = Integer.parseInt(line);
            System.out.println(x + "! = " + Factorial4.factorial(x));
        }
        // If anything goes wrong, display a generic error message
        catch (Exception e) {
            System.out.println("Invalid Input");
        }
    }
}

From source file:edu.umd.shrawanraina.SequentialPersonalizedPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(//from  w  w w  . j av a2 s .co m
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));
    options.addOption(OptionBuilder.withArgName("node").hasArg()
            .withDescription("source node (i.e., destination of the random jump)").create(SOURCE));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT) || !cmdline.hasOption(SOURCE)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPersonalizedPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    final String source = cmdline.getOptionValue(SOURCE);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    if (!graph.containsVertex(source)) {
        System.err.println("Error: source node not found in the graph!");
        System.exit(-1);
    }

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute personalized PageRank.
    PageRankWithPriors<String, Integer> ranker = new PageRankWithPriors<String, Integer>(graph,
            new Transformer<String, Double>() {
                public Double transform(String vertex) {
                    return vertex.equals(source) ? 1.0 : 0;
                }
            }, alpha);

    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:cc.vidr.datum.tools.Console.java

public static void main(String[] args) throws IOException {
    System.out.print("Warming up... ");
    System.out.flush();/*from ww w  .j ava2 s . c o  m*/
    QA.query("");
    System.out.println("Ready.");
    System.out.println("Ask me a question. Leave a blank line to exit.");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        int numServers = Server.getNumServers();
        int numFacts = Server.getNumFacts();
        System.out.print("> ");
        String q = in.readLine();
        if (q == null || q.isEmpty()) {
            System.out.println("Bye.");
            break;
        }
        Literal[] facts;
        if (q.startsWith("?-")) {
            try {
                Program program = new Program(q.substring(2));
                Clause[] query = program.parse();
                facts = Server.query(query[0].getHead());
            } catch (RecognitionException e) {
                facts = new Literal[0];
            }
        } else {
            facts = QA.query(q);
        }
        for (Literal fact : facts)
            printFact(fact, 0);
        if (facts.length == 0)
            System.out.println("I don't know.");
        if (DEBUG) {
            System.err.println((Server.getNumServers() - numServers) + " servers spawned");
            System.err.println((Server.getNumFacts() - numFacts) + " facts retrieved/generated");
        }
    }
}

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 ww  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);
}