List of usage examples for java.io BufferedReader read
public int read() throws IOException
From source file:com.interacciones.mxcashmarketdata.driver.client.DriverClient.java
public static void main(String[] args) throws Throwable { init(args);/*from w ww.j av a2 s . c om*/ NioSocketConnector connector = new NioSocketConnector(); // Configure the service. connector.setConnectTimeoutMillis(CONNECT_TIMEOUT); if (USE_CUSTOM_CODEC) { connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new SumUpProtocolCodecFactory(false))); } else { connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory())); } int[] values = new int[] {}; connector.getFilterChain().addLast("logger", new LoggingFilter()); connector.setHandler(new ClientSessionHandler(values)); long time = System.currentTimeMillis(); IoSession session; for (;;) { try { System.out.println(host + " " + port + " " + fileTest); ConnectFuture future = connector.connect(new InetSocketAddress(host, port)); future.awaitUninterruptibly(); session = future.getSession(); File file = new File(fileTest); FileInputStream is = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); int data = br.read(); int count = 0; IoBuffer ib = IoBuffer.allocate(274); ib.setAutoExpand(true); boolean flagcount = false; while (data != -1) { data = br.read(); ib.put((byte) data); if (flagcount) { count++; } if (data == 13) { count = 1; flagcount = true; LOGGER.debug(ib.toString()); } if (count == 4) { ib.flip(); session.write(ib); ib = IoBuffer.allocate(274); ib.setAutoExpand(true); flagcount = false; count = 0; //Thread.sleep(500); } } break; } catch (RuntimeIoException e) { LOGGER.error("Failed to connect."); e.printStackTrace(); Thread.sleep(5000); } } time = System.currentTimeMillis() - time; LOGGER.info("Time " + time); // wait until the summation is done session.getCloseFuture().awaitUninterruptibly(); connector.dispose(); }
From source file:GZIPcompress.java
public static void main(String[] args) throws IOException { if (args.length == 0) { System.out.println("Usage: \nGZIPcompress file\n" + "\tUses GZIP compression to compress " + "the file to test.gz"); System.exit(1);/* w ww . ja va 2 s .c o m*/ } BufferedReader in = new BufferedReader(new FileReader(args[0])); BufferedOutputStream out = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream("test.gz"))); System.out.println("Writing file"); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); System.out.println("Reading file"); BufferedReader in2 = new BufferedReader( new InputStreamReader(new GZIPInputStream(new FileInputStream("test.gz")))); String s; while ((s = in2.readLine()) != null) System.out.println(s); }
From source file:AllCapsDemo.java
License:asdf
public static void main(String[] arguments) { String sourceName = "asdf"; try {//from ww w . j a v a 2 s . co m File source = new File(sourceName); File temp = new File("cap" + sourceName + ".tmp"); FileReader fr = new FileReader(source); BufferedReader in = new BufferedReader(fr); FileWriter fw = new FileWriter(temp); BufferedWriter out = new BufferedWriter(fw); boolean eof = false; int inChar = 0; do { inChar = in.read(); if (inChar != -1) { char outChar = Character.toUpperCase((char) inChar); out.write(outChar); } else eof = true; } while (!eof); in.close(); out.close(); boolean deleted = source.delete(); if (deleted) temp.renameTo(source); } catch (Exception se) { System.out.println("Error - " + se.toString()); } }
From source file:com.util.finalProy.java
/** * @param args the command line arguments *//*www .ja v a 2 s .c o 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:BufferedCopy.java
public static void main(String[] args) throws IOException { BufferedReader inputStream = null; BufferedWriter outputStream = null; try {/* w w w . j ava 2 s . c o m*/ inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new BufferedWriter(new FileWriter("characteroutput.txt")); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } }
From source file:Server_socket.java
public static void main(String argv[]) throws Exception { int puerto = Integer.parseInt(argv[0]); //String username = argv[1]; //String password = argv[2]; String clientformat;/*from www. j a v a2 s .co m*/ String clientdata; String clientresult; String clientresource; String url_login = "http://localhost:3000/users/sign_in"; ServerSocket welcomeSocket = new ServerSocket(puerto); /*HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_login); // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); // nameValuePairs.add(new BasicNameValuePair("utf8", Character.toString('\u2713'))); nameValuePairs.add(new BasicNameValuePair("username", username)); nameValuePairs.add(new BasicNameValuePair("password", password)); // nameValuePairs.add(new BasicNameValuePair("commit", "Sign in")); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpClient.execute(httpPost); String ret = EntityUtils.tostring(response.getEntity()); System.out.println(ret); */ while (true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientformat = inFromClient.readLine(); System.out.println("FORMAT: " + clientformat); BufferedReader inFromClient1 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientdata = inFromClient1.readLine(); System.out.println("DATA: " + clientdata); BufferedReader inFromClient2 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresult = inFromClient2.readLine(); System.out.println("RESULT: " + clientresult); BufferedReader inFromClient3 = new BufferedReader( new InputStreamReader(connectionSocket.getInputStream())); clientresource = inFromClient3.readLine(); System.out.println("RESOURCE: " + clientresource); System.out.println("no pasas de aqui"); String url = "http://localhost:3000/" + clientresource + "/" + clientdata + "." + clientformat; System.out.println(url); try (InputStream is = new URL(url).openStream()) { BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } String stb = sb.toString(); System.out.println("estas aqui"); String output = null; String jsonText = stb; output = jsonText.replace("[", "").replace("]", ""); JSONObject json = new JSONObject(output); System.out.println(json.toString()); System.out.println("llegaste al final"); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); outToClient.writeBytes(json.toString()); } connectionSocket.close(); } }
From source file:TreeNode.java
public static void main(String[] argv) throws IOException { BinaryTree bt = new BinaryTree(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int val; char ch = ' '; String clearbuffer;/*from ww w. j a v a 2 s .c o m*/ do { System.out.print("Enter a number: "); val = Integer.parseInt(br.readLine()); bt.insert(val); System.out.print("Do you wish to enter more values (Y/N)....."); ch = (char) br.read(); clearbuffer = br.readLine(); } while (ch == 'y' || ch == 'Y'); System.out.println("Postorder traversal of given tree is: "); bt.postorder(); System.out.println("Preorder traversal of given tree is: "); bt.preorder(); System.out.println("Inorder traversal of given tree is: "); bt.inorder(); }
From source file:GrowBufferedReader.java
public static void main(String... args) { try {//from w ww . ja va2s. c o m BufferedReader br = new BufferedReader(car); Class<?> c = br.getClass(); Field f = c.getDeclaredField("cb"); // cb is a private field f.setAccessible(true); char[] cbVal = char[].class.cast(f.get(br)); char[] newVal = Arrays.copyOf(cbVal, cbVal.length * 2); if (args.length > 0 && args[0].equals("grow")) f.set(br, newVal); for (int i = 0; i < srcBufSize; i++) br.read(); // see if the new backing array is being used if (newVal[srcBufSize - 1] == src[srcBufSize - 1]) out.format("Using new backing array, size=%d%n", newVal.length); else out.format("Using original backing array, size=%d%n", cbVal.length); // production code should handle these exceptions more gracefully } catch (FileNotFoundException x) { x.printStackTrace(); } catch (NoSuchFieldException x) { x.printStackTrace(); } catch (IllegalAccessException x) { x.printStackTrace(); } catch (IOException x) { x.printStackTrace(); } }
From source file:HelloSmartsheet.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try {/* w ww .j a va 2 s . c o m*/ System.out.println("STARTING HelloSmartsheet..."); //Create a BufferedReader to read user input. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter Smartsheet API access token:"); String accessToken = in.readLine(); System.out.println("Fetching list of your sheets..."); //Create a connection and fetch the list of sheets connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; //Read the response line by line. while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); //Use Jackson to conver the JSON string to a List of Sheets List<Sheet> sheets = mapper.readValue(response.toString(), new TypeReference<List<Sheet>>() { }); if (sheets.size() == 0) { System.out.println("You don't have any sheets. Goodbye!"); return; } System.out.println("Total sheets: " + sheets.size()); int i = 1; for (Sheet sheet : sheets) { System.out.println(i++ + ": " + sheet.name); } System.out.print("Enter the number of the sheet you want to share: "); //Prompt the user to provide the sheet number, the email address, and the access level Integer sheetNumber = Integer.parseInt(in.readLine().trim()); //NOTE: for simplicity, error handling and input validation is neglected. Sheet chosenSheet = sheets.get(sheetNumber - 1); System.out.print("Enter an email address to share " + chosenSheet.getName() + " to: "); String email = in.readLine(); System.out.print("Choose an access level (VIEWER, EDITOR, EDITOR_SHARE, ADMIN) for " + email + ": "); String accessLevel = in.readLine(); //Create a share object Share share = new Share(); share.setEmail(email); share.setAccessLevel(accessLevel); System.out.println("Sharing " + chosenSheet.name + " to " + email + " as " + accessLevel + "."); //Create a connection. Note the SHARE_SHEET_URL uses /sheet as opposed to /sheets (with an 's') connection = (HttpURLConnection) new URL(SHARE_SHEET_URL.replace(SHEET_ID, "" + chosenSheet.getId())) .openConnection(); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); //Serialize the Share object writer.write(mapper.writeValueAsString(share)); writer.close(); //Read the response and parse the JSON reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } Result result = mapper.readValue(response.toString(), Result.class); System.out.println("Sheet shared successfully, share ID " + result.result.id); System.out.println("Press any key to quit."); in.read(); } catch (IOException e) { BufferedReader reader = new BufferedReader( new InputStreamReader(((HttpURLConnection) connection).getErrorStream())); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result result = mapper.readValue(response.toString(), Result.class); System.out.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }
From source file:Main.java
/** * Run a command and return its output./*from w w w . ja v a 2 s . c o m*/ */ public static String systemOut(String command) throws Exception { int c; String cmd[] = new String[3]; cmd[0] = System.getProperty("SHELL", "/bin/sh"); cmd[1] = "-c"; cmd[2] = command; Process p = Runtime.getRuntime().exec(cmd); BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuilder s = new StringBuilder(); while ((c = r.read()) != -1) s.append((char) c); p.waitFor(); return s.toString(); }