List of usage examples for java.io BufferedReader BufferedReader
public BufferedReader(Reader in)
From source file:com.mycompany.test.Jaroop.java
/** * This is the main program which will receive the request, calls required methods * and processes the response./*ww w.ja va 2 s.c o m*/ * @param args * @throws IOException */ public static void main(String[] args) throws IOException { Scanner scannedInput = new Scanner(System.in); String in = ""; if (args.length == 0) { System.out.println("Enter the query"); in = scannedInput.nextLine(); } else { in = args[0]; } in = in.toLowerCase().replaceAll("\\s+", "_"); int httpStatus = checkInvalidInput(in); if (httpStatus == 0) { System.out.print("Not found"); System.exit(0); } String url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + in; HttpURLConnection connection = getConnection(url); BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream())); String request = ""; StringBuilder response = new StringBuilder(); while ((request = input.readLine()) != null) { //only appending what ever is required for JSON parsing and ignoring the rest response.append("{"); //appending the key "extract" to the string so that the JSON parser can parse it's value, //also we don't need last 3 paranthesis in the response, excluding them as well. response.append(request.substring(request.indexOf("\"extract"), request.length() - 3)); } parseJSON(response.toString()); }
From source file:Main.java
public static void main(String[] args) throws Exception { try {/*ww w .ja va 2 s .com*/ String url = "jdbc:odbc:yourdatabasename"; String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; String user = "guest"; String password = "guest"; FileInputStream fis = new FileInputStream("sometextfile.txt"); Class.forName(driver); Connection connection = DriverManager.getConnection(url, user, password); Statement createTable = connection.createStatement(); createTable.executeUpdate("CREATE TABLE source_code (name char(20), source LONGTEXT)"); String ins = "INSERT INTO source_code VALUES(?,?)"; PreparedStatement statement = connection.prepareStatement(ins); statement.setString(1, "TryInputStream2"); statement.setAsciiStream(2, fis, fis.available()); int rowsUpdated = statement.executeUpdate(); System.out.println("Rows affected: " + rowsUpdated); Statement getCode = connection.createStatement(); ResultSet theCode = getCode.executeQuery("SELECT name,source FROM source_code"); BufferedReader reader = null; String input = null; while (theCode.next()) { reader = new BufferedReader(new InputStreamReader(theCode.getAsciiStream(2))); while ((input = reader.readLine()) != null) { System.out.println(input); } } connection.close(); } catch (Exception e) { System.err.println(e); } }
From source file:Main.java
public static void main(String[] args) throws Exception { try {/* w w w . j a v a2 s.c om*/ String url = "jdbc:odbc:yourdatabasename"; String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; String user = "guest"; String password = "guest"; FileInputStream fis = new FileInputStream("sometextfile.txt"); Class.forName(driver); Connection connection = DriverManager.getConnection(url, user, password); Statement createTable = connection.createStatement(); createTable.executeUpdate("CREATE TABLE source_code (name char(20), source LONGTEXT)"); String ins = "INSERT INTO source_code VALUES(?,?)"; PreparedStatement statement = connection.prepareStatement(ins); statement.setString(1, "TryInputStream2"); statement.setAsciiStream(2, fis, fis.available()); int rowsUpdated = statement.executeUpdate(); System.out.println("Rows affected: " + rowsUpdated); Statement getCode = connection.createStatement(); ResultSet theCode = getCode.executeQuery("SELECT name,source FROM source_code"); BufferedReader reader = null; String input = null; while (theCode.next()) { reader = new BufferedReader(new InputStreamReader(theCode.getAsciiStream("source"))); while ((input = reader.readLine()) != null) { System.out.println(input); } } connection.close(); } catch (Exception e) { System.err.println(e); } }
From source file:RestGetClient.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet getRequest = new HttpGet("http://localhost:10080/example/json/product/get"); 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()); //}//from w ww.ja va 2 s . com 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); } httpClient.getConnectionManager().shutdown(); }
From source file:AverageCost.java
public static void main(String[] args) throws FileNotFoundException, IOException { //Directory of the n files String directory_path = "/home/gauss/rgrunitzki/Dropbox/Profissional/UFRGS/Doutorado/Artigo TRI15/SF Experiments/IQ-Learning/"; BufferedReader reader = null; //Line to analyse String line = ""; String csvDivisor = ";"; int totalLines = 1002; int totalRows = 532; String filesToRead[] = new File(directory_path).list(); Arrays.sort(filesToRead);// w w w . j a va 2 s.c om System.out.println(filesToRead.length); List<List<DescriptiveStatistics>> summary = new ArrayList<>(); for (int i = 0; i <= totalLines; i++) { summary.add(new ArrayList<DescriptiveStatistics>()); for (int j = 0; j <= totalRows; j++) { summary.get(i).add(new DescriptiveStatistics()); } } //reads all files for (String file : filesToRead) { reader = new BufferedReader(new FileReader(directory_path + file)); int lineCounter = 0; //reads all file's line while ((line = reader.readLine()) != null) { if (lineCounter > 0) { String[] rows = line.trim().split(csvDivisor); //reads all line's row for (int r = 0; r < rows.length; r++) { summary.get(lineCounter).get(r).addValue(Double.parseDouble(rows[r])); } } lineCounter++; } //System.out.println(file.split("/")[file.split("/").length - 1] + csvDivisor + arithmeticMean(avgCost) + csvDivisor + standardDeviation(avgCost)); } //generate mean and standard deviation; for (List<DescriptiveStatistics> summaryLines : summary) { System.out.println(); for (DescriptiveStatistics summaryLineRow : summaryLines) { System.out.print(summaryLineRow.getMean() + ";" + summaryLineRow.getStandardDeviation() + ";"); } } }
From source file:com.util.finalProy.java
/** * @param args the command line arguments */// w w w .ja v a2s . co m public static void main(String[] args) throws JSONException { // TODO code application logic her System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON"); String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json"; System.out.println("Requested URL:" + myURL); StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try { URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) { urlConn.setReadTimeout(60 * 1000); } if (urlConn != null && urlConn.getInputStream() != null) { in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) { int cp; while ((cp = bufferedReader.read()) != -1) { sb.append((char) cp); } bufferedReader.close(); } } in.close(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Exception while calling URL:" + myURL, e); } String jsonResult = sb.toString(); System.out.println(sb.toString()); System.out.println( "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n"); JSONObject objJason = new JSONObject(jsonResult); JSONArray dataJson = new JSONArray(); dataJson = objJason.getJSONArray("data"); System.out.println("objeto normal 1 " + dataJson.toString()); // // System.out.println( "\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n"); String jsonString2 = dataJson.toString(); String temp = dataJson.toString(); temp = jsonString2.replace("[", ""); jsonString2 = temp.replace("]", ""); System.out.println("new json string" + jsonString2); JSONObject objJson2 = new JSONObject(jsonString2); System.out.println("el objeto simple json es " + objJson2.toString()); System.out.println( "\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n"); String account1 = objJson2.optString("account"); System.out.println(account1); JSONObject objJson3 = new JSONObject(account1); System.out.println("el ULTIMO OBJETO SIMPLE ES " + objJson3.toString()); System.out.println( "\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n"); String firstName = objJson3.getString("first_name"); System.out.println(firstName); System.out.println(objJson3.get("id")); System.out.println( "\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n"); Gson gson = new Gson(); Account account = gson.fromJson(objJson3.toString(), Account.class); System.out.println(account.getFirst_name()); System.out.println(account.getCreation()); }
From source file:com.rest.samples.getTipoCambioBanxico.java
public static void main(String[] args) { String url = "http://www.banxico.org.mx/tipcamb/llenarTiposCambioAction.do?idioma=sp"; try {/*from ww w . j a va2 s . c o m*/ HttpClient hc = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); request.setHeader("User-Agent", "Mozilla/5.0"); request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); HttpResponse res = hc.execute(request); if (res.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode()); } BufferedReader rd = new BufferedReader(new InputStreamReader(res.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } Document doc = Jsoup.parse(result.toString()); Element tipoCambioFix = doc.getElementById("FIX_DATO"); System.out.println(tipoCambioFix.text()); } catch (IOException ex) { Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.aj.hangman.HangmanReq.java
public static void main(String[] args) { HangmanDict dictionary = new HangmanDict(); try {/*from w ww . j a v a 2 s . com*/ BufferedReader input = new BufferedReader(new InputStreamReader( new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu").openStream())); String info = input.readLine(); JSONParser parser = new JSONParser(); Object obj; try { obj = parser.parse(info); JSONObject retJson = (JSONObject) obj; TOKEN = (String) retJson.get("token"); STATUS = (String) retJson.get("status"); STATE = (String) retJson.get("state"); REM = (Long) retJson.get("remaining_guesses"); PREM = REM; System.out.println("State:: " + STATE); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } while ("ALIVE".equalsIgnoreCase(STATUS)) { // call make guess function, returns character guess = dictionary.makeGuess(STATE); System.out.println("Guessed:: " + guess); // call the url to update BufferedReader reInput = new BufferedReader( new InputStreamReader(new URL("http://gallows.hulu.com/play?code=gudehosa@usc.edu" + String.format("&token=%s&guess=%s", TOKEN, guess)).openStream())); // parse the url to get the updated value String reInfo = reInput.readLine(); JSONParser reParser = new JSONParser(); Object retObj = reParser.parse(reInfo); JSONObject retJson = (JSONObject) retObj; STATUS = (String) retJson.get("status"); STATE = (String) retJson.get("state"); REM = (Long) retJson.get("remaining_guesses"); System.out.println("State:: " + STATE); } if ("DEAD".equalsIgnoreCase(STATUS)) { // print lost System.out.println("You LOOSE: DEAD"); } else if ("FREE".equalsIgnoreCase(STATUS)) { // print free System.out.println("You WIN: FREE"); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:StreamTaggerDemo.java
public static void main(String args[]) { try {//from w w w . j a v a2 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 StreamTaggerDemo <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.xml"; // StreamTagger tagger = new StreamTagger((Reader) br, confPath); StreamTagger tagger = new StreamTagger((Reader) br); // BufferedReader is = new BufferedReader(System.in); while (tagger.hasNext()) { Token token = tagger.next(); System.out.println(token.toString() + "\t(" + token.getBasicString() + ")" + "\t" + token.getPos() + "(" + token.start() + "," + token.end() + "," + token.length() + ")\t" + token.getReading() + "\t" + token.getPronunciation()); } } catch (Exception e) { e.printStackTrace(); } }
From source file:com.linkedin.pinot.broker.broker.BrokerServerBuilderTest.java
public static void main(String[] args) throws Exception { PropertiesConfiguration config = new PropertiesConfiguration( new File(BrokerServerBuilderTest.class.getClassLoader().getResource("broker.properties").toURI())); final BrokerServerBuilder bld = new BrokerServerBuilder(config, null, null, null); bld.buildNetwork();// www. ja va2 s .co m bld.buildHTTP(); bld.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { bld.stop(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (true) { String command = br.readLine(); if (command.equals("exit")) { bld.stop(); } } }