List of usage examples for java.io BufferedReader readLine
public String readLine() throws IOException
From source file:EchoClient.java
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try {/* w w w. jav a 2 s . c o m*/ serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); String inputLine, outputLine; KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; } out.close(); in.close(); clientSocket.close(); serverSocket.close(); }
From source file:ExecuteSQL.java
public static void main(String[] args) { Connection conn = null; // Our JDBC connection to the database server try {/* w w w. j a v a 2 s .com*/ String driver = null, url = null, user = "", password = ""; // Parse all the command-line arguments for (int n = 0; n < args.length; n++) { if (args[n].equals("-d")) driver = args[++n]; else if (args[n].equals("-u")) user = args[++n]; else if (args[n].equals("-p")) password = args[++n]; else if (url == null) url = args[n]; else throw new IllegalArgumentException("Unknown argument."); } // The only required argument is the database URL. if (url == null) throw new IllegalArgumentException("No database specified"); // If the user specified the classname for the DB driver, load // that class dynamically. This gives the driver the opportunity // to register itself with the DriverManager. if (driver != null) Class.forName(driver); // Now open a connection the specified database, using the // user-specified username and password, if any. The driver // manager will try all of the DB drivers it knows about to try to // parse the URL and connect to the DB server. conn = DriverManager.getConnection(url, user, password); // Now create the statement object we'll use to talk to the DB Statement s = conn.createStatement(); // Get a stream to read from the console BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Loop forever, reading the user's queries and executing them while (true) { System.out.print("sql> "); // prompt the user System.out.flush(); // make the prompt appear now. String sql = in.readLine(); // get a line of input from user // Quit when the user types "quit". if ((sql == null) || sql.equals("quit")) break; // Ignore blank lines if (sql.length() == 0) continue; // Now, execute the user's line of SQL and display results. try { // We don't know if this is a query or some kind of // update, so we use execute() instead of executeQuery() // or executeUpdate() If the return value is true, it was // a query, else an update. boolean status = s.execute(sql); // Some complex SQL queries can return more than one set // of results, so loop until there are no more results do { if (status) { // it was a query and returns a ResultSet ResultSet rs = s.getResultSet(); // Get results printResultsTable(rs, System.out); // Display them } else { // If the SQL command that was executed was some // kind of update rather than a query, then it // doesn't return a ResultSet. Instead, we just // print the number of rows that were affected. int numUpdates = s.getUpdateCount(); System.out.println("Ok. " + numUpdates + " rows affected."); } // Now go see if there are even more results, and // continue the results display loop if there are. status = s.getMoreResults(); } while (status || s.getUpdateCount() != -1); } // If a SQLException is thrown, display an error message. // Note that SQLExceptions can have a general message and a // DB-specific message returned by getSQLState() catch (SQLException e) { System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState()); } // Each time through this loop, check to see if there were any // warnings. Note that there can be a whole chain of warnings. finally { // print out any warnings that occurred SQLWarning w; for (w = conn.getWarnings(); w != null; w = w.getNextWarning()) System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState()); } } } // Handle exceptions that occur during argument parsing, database // connection setup, etc. For SQLExceptions, print the details. catch (Exception e) { System.err.println(e); if (e instanceof SQLException) System.err.println("SQL State: " + ((SQLException) e).getSQLState()); System.err.println( "Usage: java ExecuteSQL [-d <driver>] " + "[-u <user>] [-p <password>] <database URL>"); } // Be sure to always close the database connection when we exit, // whether we exit because the user types 'quit' or because of an // exception thrown while setting things up. Closing this connection // also implicitly closes any open statements and result sets // associated with it. finally { try { conn.close(); } catch (Exception e) { } } }
From source file:com.twentyn.chemicalClassifier.Runner.java
public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(args[0])); BufferedWriter writer = new BufferedWriter(new FileWriter(args[1])); try {//w w w . j a v a2s . c o m Oscar oscar = new Oscar(); String line = null; /* NOTE: this is exactly the wrong way to write a TSV reader. Caveat emptor. * See http://tburette.github.io/blog/2014/05/25/so-you-want-to-write-your-own-CSV-code/ * and then use org.apache.commons.csv.CSVParser instead. */ while ((line = reader.readLine()) != null) { // TSV means split on tabs! Nothing else will do. List<String> fields = Arrays.asList(line.split("\t")); // Choke if our invariants aren't satisfied. We expect ever line to have a name and an InChI. if (fields.size() != 2) { throw new RuntimeException( String.format("Found malformed line (all lines must have two fields: %s", line)); } String name = fields.get(1); List<ResolvedNamedEntity> entities = oscar.findAndResolveNamedEntities(name); System.out.println("**********"); System.out.println("Name: " + name); List<String> outputFields = new ArrayList<>(fields.size() + 1); outputFields.addAll(fields); if (entities.size() == 0) { System.out.println("No match"); outputFields.add("noMatch"); } else if (entities.size() == 1) { ResolvedNamedEntity entity = entities.get(0); NamedEntity ne = entity.getNamedEntity(); if (ne.getStart() != 0 || ne.getEnd() != name.length()) { System.out.println("Partial match"); printEntity(entity); outputFields.add("partialMatch"); } else { System.out.println("Exact match"); printEntity(entity); outputFields.add("exactMatch"); List<ChemicalStructure> structures = entity.getChemicalStructures(FormatType.STD_INCHI); for (ChemicalStructure s : structures) { outputFields.add(s.getValue()); } } } else { // Multiple matches found! System.out.println("Multiple matches"); for (ResolvedNamedEntity e : entities) { printEntity(e); } outputFields.add("multipleMatches"); } writer.write(String.join("\t", outputFields)); writer.newLine(); } } finally { writer.flush(); writer.close(); } }
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 . ja v a2 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); } }
From source file:org.jfree.chart.demo.Display.java
/** * Launch the application.//from w w w. j a v a 2 s. c om */ public static void main(String[] args) throws IOException { EventQueue.invokeLater(new Runnable() { public void run() { try { Display window = new Display(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } //////////// } }); try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s; File dataFile = new File("data.txt"); FileWriter fw = new FileWriter(dataFile); BufferedWriter bw = new BufferedWriter(fw); DataParser datIn = new DataParser(effectiveX, effectiveY); //while(!enabled){}//spin until enabled while ((s = in.readLine()) != null && s.length() != 0 && enabled) { // System.out.println(s); if (datIn.parseString(s)) { bw.write(s); bw.write('\n'); bw.flush(); panel_1.plotCoords(datIn.getX(), datIn.getFlippedY()); TimeElapsed.setText(Double.toString(datIn.getTime())); } } bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:ExecDemoWait.java
public static void main(String argv[]) throws IOException { // A Runtime object has methods for dealing with the OS Runtime r = Runtime.getRuntime(); Process p; // Process tracks one external native process BufferedReader is; // reader for output of process String line;/* w w w . ja v a 2 s. c o m*/ // Our argv[0] contains the program to run; remaining elements // of argv contain args for the target program. This is just // what is needed for the String[] form of exec. p = r.exec(argv); System.out.println("In Main after exec"); // getInputStream gives an Input stream connected to // the process p's standard output. Just use it to make // a BufferedReader to readLine() what the program writes out. is = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = is.readLine()) != null) System.out.println(line); System.out.println("In Main after EOF"); System.out.flush(); try { p.waitFor(); // wait for process to complete } catch (InterruptedException e) { System.err.println(e); // "Can'tHappen" return; } System.err.println("Process done, exit status was " + p.exitValue()); return; }
From source file:com.idega.util.Stripper.java
public static void main(String[] args) { // Stripper stripper1 = new Stripper(); if (args.length != 2) { System.err.println("Auli. tt a hafa tvo parametra me essu, innskr og tskr"); return;/* w ww.j a v a 2 s. c o m*/ } BufferedReader in = null; BufferedWriter out = null; try { in = new BufferedReader(new FileReader(args[0])); } catch (java.io.FileNotFoundException e) { System.err.println("Auli. Error : " + e.toString()); return; } try { out = new BufferedWriter(new FileWriter(args[1])); } catch (java.io.IOException e) { System.err.println("Auli. Error : " + e.toString()); IOUtils.closeQuietly(in); return; } try { String input = in.readLine(); int count = 0; while (input != null) { int index = input.indexOf("\\CVS\\"); if (index > -1) { System.out.println("Skipping : " + input); count++; } else { out.write(input); out.newLine(); } input = in.readLine(); } System.out.println("Skipped : " + count); } catch (java.io.IOException e) { System.err.println("Error reading or writing file : " + e.toString()); } try { in.close(); out.close(); } catch (java.io.IOException e) { System.err.println("Error closing files : " + e.toString()); } }
From source file:com.github.brandtg.stl.StlDecomposition.java
/** * Runs STL on a CSV of time,measure./* w w w . j a va2 s . c o m*/ * * <p> * Outputs a CSV of time,measure,trend,seasonal,remainder. * </p> * * @param args * args[0] = numberOfObservations * @throws Exception * If could not process data */ public static void main(String[] args) throws Exception { List<Number> times = new ArrayList<Number>(); List<Number> measures = new ArrayList<Number>(); // Read from STDIN String line; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while ((line = reader.readLine()) != null) { String[] tokens = line.split(","); times.add(Long.valueOf(tokens[0])); measures.add(Double.valueOf(tokens[1])); } // Compute STL StlDecomposition stl = new StlDecomposition(Integer.valueOf(args[0])); stl.getConfig().setSeasonalComponentBandwidth(Double.valueOf( System.getProperty("seasonal.bandwidth", String.valueOf(StlConfig.DEFAULT_SEASONAL_BANDWIDTH)))); stl.getConfig().setTrendComponentBandwidth(Double .valueOf(System.getProperty("trend.bandwidth", String.valueOf(StlConfig.DEFAULT_TREND_BANDWIDTH)))); stl.getConfig().setNumberOfInnerLoopPasses(Integer .valueOf(System.getProperty("inner.loop", String.valueOf(StlConfig.DEFAULT_INNER_LOOP_PASSES)))); StlResult res = stl.decompose(times, measures); // Output to STDOUT for (int i = 0; i < times.size(); i++) { System.out.println(String.format("%d,%02f,%02f,%02f,%02f", (long) res.getTimes()[i], res.getSeries()[i], res.getTrend()[i], res.getSeasonal()[i], res.getRemainder()[i])); } }
From source file:com.xiangzhurui.util.email.SMTPMail.java
public static void main(String[] args) { String sender, recipient, subject, filename, server, cc; List<String> ccList = new ArrayList<String>(); BufferedReader stdin; FileReader fileReader = null; Writer writer;//from w w w .j av a2 s.c o m SimpleSMTPHeader header; SMTPClient client; if (args.length < 1) { System.err.println("Usage: mail smtpserver"); System.exit(1); } server = args[0]; stdin = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("From: "); System.out.flush(); sender = stdin.readLine(); System.out.print("To: "); System.out.flush(); recipient = stdin.readLine(); System.out.print("Subject: "); System.out.flush(); subject = stdin.readLine(); header = new SimpleSMTPHeader(sender, recipient, subject); while (true) { System.out.print("CC <enter one address per line, hit enter to end>: "); System.out.flush(); cc = stdin.readLine(); if (cc == null || cc.length() == 0) { break; } header.addCC(cc.trim()); ccList.add(cc.trim()); } 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()); } client = new SMTPClient(); client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); client.connect(server); if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) { client.disconnect(); System.err.println("SMTP server refused connection."); System.exit(1); } client.login(); client.setSender(sender); client.addRecipient(recipient); for (String recpt : ccList) { client.addRecipient(recpt); } writer = client.sendMessageData(); if (writer != null) { writer.write(header.toString()); Util.copyReader(fileReader, writer); writer.close(); client.completePendingCommand(); } if (fileReader != null) { fileReader.close(); } client.logout(); client.disconnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }
From source file:examples.nntp.PostMessage.java
public static void main(String[] args) { String from, subject, newsgroup, filename, server, organization; String references;/*from w w w . j av a 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 && references.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), true)); 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(); } } if (fileReader != null) { fileReader.close(); } client.logout(); client.disconnect(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } }