List of usage examples for java.io PrintWriter PrintWriter
public PrintWriter(File file) throws FileNotFoundException
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 a2s . 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:edu.msu.cme.rdp.multicompare.Reprocess.java
/** * This class reprocesses the classification results (allrank output) and print out hierarchy output file, based on the confidence cutoff; * and print out only the detail classification results with assignment at certain rank with confidence above the cutoff or/and matching a given taxon. * @param args/* w ww. j av a 2 s .c o m*/ * @throws Exception */ public static void main(String[] args) throws Exception { PrintWriter assign_out = new PrintWriter(new NullWriter()); float conf = 0.8f; PrintStream heir_out = null; String hier_out_filename = null; ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank; String rank = null; String taxonFilterFile = null; String train_propfile = null; String gene = null; List<MCSample> samples = new ArrayList(); try { CommandLine line = new PosixParser().parse(options, args); if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) { hier_out_filename = line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT); heir_out = new PrintStream(hier_out_filename); } else { throw new Exception( "It make sense to provide output filename for " + CmdOptions.HIER_OUTFILE_LONG_OPT); } if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) { assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT)); } if (line.hasOption(CmdOptions.RANK_SHORT_OPT)) { rank = line.getOptionValue(CmdOptions.RANK_SHORT_OPT); } if (line.hasOption(CmdOptions.TAXON_SHORT_OPT)) { taxonFilterFile = line.getOptionValue(CmdOptions.TAXON_SHORT_OPT); } if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) { conf = Float.parseFloat(line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT)); if (conf < 0 || conf > 1) { throw new IllegalArgumentException("Confidence must be in the range [0,1]"); } } if (line.hasOption(CmdOptions.FORMAT_SHORT_OPT)) { String f = line.getOptionValue(CmdOptions.FORMAT_SHORT_OPT); if (f.equalsIgnoreCase("allrank")) { format = ClassificationResultFormatter.FORMAT.allRank; } else if (f.equalsIgnoreCase("fixrank")) { format = ClassificationResultFormatter.FORMAT.fixRank; } else if (f.equalsIgnoreCase("db")) { format = ClassificationResultFormatter.FORMAT.dbformat; } else if (f.equalsIgnoreCase("filterbyconf")) { format = ClassificationResultFormatter.FORMAT.filterbyconf; } else { throw new IllegalArgumentException( "Not valid output format, only allrank, fixrank, filterbyconf and db allowed"); } } if (line.hasOption(CmdOptions.TRAINPROPFILE_SHORT_OPT)) { if (gene != null) { throw new IllegalArgumentException( "Already specified the gene from the default location. Can not specify train_propfile"); } else { train_propfile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT); } } if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) { if (train_propfile != null) { throw new IllegalArgumentException( "Already specified train_propfile. Can not specify gene any more"); } gene = line.getOptionValue(CmdOptions.GENE_SHORT_OPT).toLowerCase(); if (!gene.equals(ClassifierFactory.RRNA_16S_GENE) && !gene.equals(ClassifierFactory.FUNGALLSU_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_warcup_GENE) && !gene.equals(ClassifierFactory.FUNGALITS_unite_GENE)) { throw new IllegalArgumentException(gene + " is NOT valid, only allows " + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", " + ClassifierFactory.FUNGALITS_warcup_GENE + " and " + ClassifierFactory.FUNGALITS_unite_GENE); } } args = line.getArgs(); if (args.length < 1) { throw new Exception("Incorrect number of command line arguments"); } for (String arg : args) { String[] inFileNames = arg.split(","); String inputFile = inFileNames[0]; File idmappingFile = null; if (inFileNames.length == 2) { idmappingFile = new File(inFileNames[1]); if (!idmappingFile.exists()) { System.err.println("Failed to find input file \"" + inFileNames[1] + "\""); return; } } MCSample nextSample = new MCSampleResult(inputFile, idmappingFile); samples.add(nextSample); } } catch (Exception e) { System.out.println("Command Error: " + e.getMessage()); new HelpFormatter().printHelp(120, "Reprocess [options] <Classification_allrank_result>[,idmappingfile] ...", "", options, ""); return; } if (train_propfile == null && gene == null) { gene = ClassifierFactory.RRNA_16S_GENE; } HashSet<String> taxonFilter = null; if (taxonFilterFile != null) { taxonFilter = readTaxonFilterFile(taxonFilterFile); } MultiClassifier multiClassifier = new MultiClassifier(train_propfile, gene); DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(heir_out, samples); MultiClassifierResult result = multiClassifier.multiClassificationParser(samples, conf, assign_out, format, rank, taxonFilter); result.getRoot().topDownVisit(printVisitor); assign_out.close(); heir_out.close(); if (multiClassifier.hasCopyNumber()) { // print copy number corrected counts File cn_corrected_s = new File(new File(hier_out_filename).getParentFile(), "cncorrected_" + hier_out_filename); PrintStream cn_corrected_hier_out = new PrintStream(cn_corrected_s); printVisitor = new DefaultPrintVisitor(cn_corrected_hier_out, samples, true); result.getRoot().topDownVisit(printVisitor); cn_corrected_hier_out.close(); } }
From source file:Printf3.java
public static void main(String[] args) { double price = 44.95; double tax = 7.75; double amountDue = price * (1 + tax / 100); PrintWriter out = new PrintWriter(System.out); Printf3.fprint(out, "Amount due = %8.2f\n", amountDue); out.flush();/* w w w. ja va 2 s. c o m*/ }
From source file:examples.nntp.PostMessage.java
public static void main(String[] args) { String from, subject, newsgroup, filename, server, organization; String references;/*from www.ja v a2s .co 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); } }
From source file:edu.byu.nlp.data.app.DataExporter.java
public static void main(String[] args) throws IOException { args = new ArgumentParser(DataExporter.class).parseArgs(args).getPositionalArgs(); RandomGenerator rnd = new MersenneTwister(); Dataset dataset = readData(rnd);/* w w w .j ava2s.c o m*/ Iterable<String> it = Iterables.transform(dataset, new Instance2SVMLitePlus()); if (args.length < 1) { Writers.writeLines(new PrintWriter(new BufferedOutputStream(System.out)), it); } else { Files2.writeLines(it, args[0]); } }
From source file:BookRank.java
/** Grab the sales rank off the web page and log it. */ public static void main(String[] args) throws Exception { Properties p = new Properties(); String title = p.getProperty("title", "NO TITLE IN PROPERTIES"); // The url must have the "isbn=" at the very end, or otherwise // be amenable to being string-catted to, like the default. String url = p.getProperty("url", "http://test.ing/test.cgi?isbn="); // The 10-digit ISBN for the book. String isbn = p.getProperty("isbn", "0000000000"); // The RE pattern (MUST have ONE capture group for the number) String pattern = p.getProperty("pattern", "Rank: (\\d+)"); // Looking for something like this in the input: // <b>QuickBookShop.web Sales Rank: </b> // 26,252/* w w w. ja v a 2 s. com*/ // </font><br> Pattern r = Pattern.compile(pattern); // Open the URL and get a Reader from it. BufferedReader is = new BufferedReader(new InputStreamReader(new URL(url + isbn).openStream())); // Read the URL looking for the rank information, as // a single long string, so can match RE across multi-lines. String input = "input from console"; // System.out.println(input); // If found, append to sales data file. Matcher m = r.matcher(input); if (m.find()) { PrintWriter pw = new PrintWriter(new FileWriter(DATA_FILE, true)); String date = // `date +'%m %d %H %M %S %Y'`; new SimpleDateFormat("MM dd hh mm ss yyyy ").format(new Date()); // Paren 1 is the digits (and maybe ','s) that matched; remove comma Matcher noComma = Pattern.compile(",").matcher(m.group(1)); pw.println(date + noComma.replaceAll("")); pw.close(); } else { System.err.println("WARNING: pattern `" + pattern + "' did not match in `" + url + isbn + "'!"); } // Whether current data found or not, draw the graph, using // external plotting program against all historical data. // Could use gnuplot, R, any other math/graph program. // Better yet: use one of the Java plotting APIs. String gnuplot_cmd = "set term png\n" + "set output \"" + GRAPH_FILE + "\"\n" + "set xdata time\n" + "set ylabel \"Book sales rank\"\n" + "set bmargin 3\n" + "set logscale y\n" + "set yrange [1:60000] reverse\n" + "set timefmt \"%m %d %H %M %S %Y\"\n" + "plot \"" + DATA_FILE + "\" using 1:7 title \"" + title + "\" with lines\n"; Process proc = Runtime.getRuntime().exec("/usr/local/bin/gnuplot"); PrintWriter gp = new PrintWriter(proc.getOutputStream()); gp.print(gnuplot_cmd); gp.close(); }
From source file:com.galois.fiveui.HeadlessRunner.java
/** * @param args list of headless run description filenames * @throws IOException//from ww w . j a v a 2s .co m * @throws URISyntaxException * @throws ParseException */ @SuppressWarnings("static-access") public static void main(final String[] args) throws IOException, URISyntaxException, ParseException { // Setup command line options Options options = new Options(); Option help = new Option("h", "print this help message"); Option output = OptionBuilder.withArgName("outfile").hasArg().withDescription("write output to file") .create("o"); Option report = OptionBuilder.withArgName("report directory").hasArg() .withDescription("write HTML reports to given directory").create("r"); options.addOption(output); options.addOption(report); options.addOption("v", false, "verbose output"); options.addOption("vv", false, "VERY verbose output"); options.addOption(help); // Parse command line options CommandLineParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Command line option parsing failed. Reason: " + e.getMessage()); System.exit(1); } // Display help if requested if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("headless <input file 1> [<input file 2> ...]", options); System.exit(1); } // Set logging levels BasicConfigurator.configure(); Logger fiveuiLogger = Logger.getLogger("com.galois.fiveui"); Logger rootLogger = Logger.getRootLogger(); if (cmd.hasOption("v")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.ERROR); } else if (cmd.hasOption("vv")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.DEBUG); } else { fiveuiLogger.setLevel(Level.ERROR); rootLogger.setLevel(Level.ERROR); } // Setup output file if requested PrintWriter outStream = null; if (cmd.hasOption("o")) { String outfile = cmd.getOptionValue("o"); try { outStream = new PrintWriter(new BufferedWriter(new FileWriter(outfile))); } catch (IOException e) { System.err.println("Could not open outfile for writing: " + cmd.getOptionValue("outfile")); System.exit(1); } } else { outStream = new PrintWriter(new BufferedWriter(new PrintWriter(System.out))); } // Setup HTML reports directory before the major work happens in case we // have to throw an exception. PrintWriter summaryFile = null; PrintWriter byURLFile = null; PrintWriter byRuleFile = null; if (cmd.hasOption("r")) { String repDir = cmd.getOptionValue("r"); try { File file = new File(repDir); if (!file.exists()) { file.mkdir(); logger.info("report directory created: " + repDir); } else { logger.info("report directory already exists!"); } summaryFile = new PrintWriter(new FileWriter(repDir + File.separator + "summary.html")); byURLFile = new PrintWriter(new FileWriter(repDir + File.separator + "byURL.html")); byRuleFile = new PrintWriter(new FileWriter(repDir + File.separator + "byRule.html")); } catch (IOException e) { System.err.println("could not open report directory / files for writing"); System.exit(1); } } // Major work: process input files ImmutableList<Result> results = null; for (String in : cmd.getArgs()) { HeadlessRunDescription descr = HeadlessRunDescription.parse(in); logger.debug("invoking headless run..."); BatchRunner runner = new BatchRunner(); results = runner.runHeadless(descr); logger.debug("runHeadless returned " + results.size() + " results"); // write results to the output stream as we go for (Result result : results) { outStream.println(result.toString()); } outStream.flush(); } outStream.close(); // Write report files if requested if (cmd.hasOption("r") && results != null) { Reporter kermit = new Reporter(results); summaryFile.write(kermit.getSummary()); summaryFile.close(); byURLFile.write(kermit.getByURL()); byURLFile.close(); byRuleFile.write(kermit.getByRule()); byRuleFile.close(); } }
From source file:ca.cutterslade.match.scheduler.Main.java
public static void main(final String[] args) throws InterruptedException { final CommandLineParser parser = new PosixParser(); try {/*from w ww . j a va2s.c om*/ final CommandLine line = parser.parse(OPTIONS, args); final int teams = Integer.parseInt(line.getOptionValue('t')); final int tiers = Integer.parseInt(line.getOptionValue('r')); final int gyms = Integer.parseInt(line.getOptionValue('g')); final int courts = Integer.parseInt(line.getOptionValue('c')); final int times = Integer.parseInt(line.getOptionValue('m')); final int days = Integer.parseInt(line.getOptionValue('d')); final int size = Integer.parseInt(line.getOptionValue('z')); final Configuration config; if (line.hasOption("random")) config = Configuration.RANDOM_CONFIGURATION; else config = new Configuration(ImmutableMap.<SadFaceFactor, Integer>of(), line.hasOption("randomMatches"), line.hasOption("randomSlots"), line.hasOption("randomDays")); final Scheduler s = new Scheduler(config, teams, tiers, gyms, courts, times, days, size); System.out.println(summary(s)); } catch (final ParseException e) { final HelpFormatter f = new HelpFormatter(); final PrintWriter pw = new PrintWriter(System.err); f.printHelp(pw, 80, "match-scheduler", null, OPTIONS, 2, 2, null, true); pw.println( "For example: match-scheduler -t 48 -r 3 -d 12 -m 2 -g 3 -c 2 -z 4 --randomMatches --randomSlots"); pw.close(); } }
From source file:Printf4.java
public static void main(String[] args) { double price = 44.95; double tax = 7.75; double amountDue = price * (1 + tax / 100); PrintWriter out = new PrintWriter(System.out); /* This call will throw an exception--note the %% */ Printf4.fprint(out, "Amount due = %%8.2f\n", amountDue); out.flush();//from w ww. ja v a 2 s . c o m }
From source file:org.jfree.chart.demo.ImageMapDemo7.java
/** * Starting point for the demo./*from ww w.j av a 2s . c om*/ * * @param args ignored. */ public static void main(final String[] args) { final XYDataset data = new SampleXYDataset2(); final JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot Demo", "X", "Y", data, PlotOrientation.VERTICAL, true, true, false); // final Legend legend = chart.getLegend(); // if (legend instanceof StandardLegend) { // final StandardLegend sl = (StandardLegend) legend; // sl.setDisplaySeriesShapes(true); //} final NumberAxis domainAxis = (NumberAxis) chart.getXYPlot().getDomainAxis(); domainAxis.setAutoRangeIncludesZero(false); chart.setBackgroundPaint(java.awt.Color.white); // **************************************************************************** // * JFREECHART DEVELOPER GUIDE * // * The JFreeChart Developer Guide, written by David Gilbert, is available * // * to purchase from Object Refinery Limited: * // * * // * http://www.object-refinery.com/jfreechart/guide.html * // * * // * Sales are used to provide funding for the JFreeChart project - please * // * support us so that we can continue developing free software. * // **************************************************************************** // save it to an image try { final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection()); final File file1 = new File("scatter100.png"); ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info); // write an HTML page incorporating the image with an image map final File file2 = new File("scatter100.html"); final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); final PrintWriter writer = new PrintWriter(out); writer.println("<HTML>"); writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>"); writer.println("<BODY>"); // ChartUtilities.writeImageMap(writer, "chart", info); writer.println("<IMG SRC=\"scatter100.png\" " + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">"); writer.println("</BODY>"); writer.println("</HTML>"); writer.close(); } catch (IOException e) { System.out.println(e.toString()); } }