Example usage for java.io PrintWriter PrintWriter

List of usage examples for java.io PrintWriter PrintWriter

Introduction

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

Prototype

public PrintWriter(File file) throws FileNotFoundException 

Source Link

Document

Creates a new PrintWriter, without automatic line flushing, with the specified file.

Usage

From source file:ctrus.pa.bow.java.JavaBagOfWords.java

public static void main(String[] args) throws Exception {
    // Parse the command line input
    JavaBOWOptions opts = JavaBOWOptions.Factory.getInstance();
    opts.parseCLI(args);/*  ww w. ja v  a  2s  . co  m*/
    if (opts.hasOption(DefaultOptions.PRINT_HELP)) {
        opts.printHelp("HELP", new PrintWriter(System.out));
    } else {
        JavaBagOfWords jBow = new JavaBagOfWords();
        jBow.init(opts);
        jBow.process();
    }
}

From source file:is.landsbokasafn.deduplicator.indexer.IndexingLauncher.java

public static void main(String[] args) throws Exception {
    loadConfiguration();/*from w  w  w . j  a va 2  s.  c  om*/

    // Set default values for all settings
    boolean verbose = readBooleanConfig(VERBOSE_CONF_KEY, true);
    boolean etag = readBooleanConfig(ETAG_CONF_KEY, false);
    boolean canonical = readBooleanConfig(CANONICAL_CONF_KEY, true);
    boolean indexURL = readBooleanConfig(INDEX_URL_KEY, true);
    boolean addToIndex = readBooleanConfig(ADD_TO_INDEX_CONF_KEY, false);
    String mimefilter = readStringConfig(MIME_CONF_KEY, "^text/.*");
    boolean whitelist = readBooleanConfig(WHITELIST_CONF_KEY, false);
    String iteratorClassName = readStringConfig(ITERATOR_CONF_KEY, WarcIterator.class.getName());

    // Parse command line options       
    CommandLineParser clp = new CommandLineParser(args, new PrintWriter(System.out));
    Option[] opts = clp.getCommandLineOptions();
    for (int i = 0; i < opts.length; i++) {
        Option opt = opts[i];
        switch (opt.getId()) {
        case 'w':
            whitelist = true;
            break;
        case 'a':
            addToIndex = true;
            break;
        case 'e':
            etag = true;
            break;
        case 'h':
            clp.usage(0);
            break;
        case 'i':
            iteratorClassName = opt.getValue();
            break;
        case 'm':
            mimefilter = opt.getValue();
            break;
        case 'u':
            indexURL = false;
            break;
        case 's':
            canonical = false;
            break;
        case 'v':
            verbose = true;
            break;
        }
    }

    if (!indexURL && canonical) {
        canonical = false;
    }

    List<String> cargs = clp.getCommandLineArguments();
    if (cargs.size() != 2) {
        // Should be exactly two arguments. Source and target!
        clp.usage(0);
    }

    String source = cargs.get(0);
    String target = cargs.get(1);

    // Load the CrawlDataIterator
    CrawlDataIterator iterator = (CrawlDataIterator) Class.forName(iteratorClassName).newInstance();

    // Print initial stuff
    System.out.println("Indexing: " + source);
    System.out.println(" - Index URL: " + indexURL);
    System.out.println(" - Mime filter: " + mimefilter + " (" + (whitelist ? "whitelist" : "blacklist") + ")");
    System.out.println(" - Includes" + (canonical ? " <canonical URL>" : "") + (etag ? " <etag>" : ""));
    System.out.println(" - Iterator: " + iteratorClassName);
    System.out.println("   - " + iterator.getSourceType());
    System.out.println("Target: " + target);
    if (addToIndex) {
        System.out.println(" - Add to existing index (if any)");
    } else {
        System.out.println(" - New index (erases any existing index at " + "that location)");
    }

    iterator.initialize(source);

    // Create the index
    long start = System.currentTimeMillis();
    IndexBuilder di = new IndexBuilder(target, indexURL, canonical, etag, addToIndex);
    di.writeToIndex(iterator, mimefilter, !whitelist, verbose);

    // Clean-up
    di.close();

    System.out.println("Total run time: "
            + DateUtils.formatMillisecondsToConventional(System.currentTimeMillis() - start));
}

From source file:com.tamingtext.tagging.LuceneTagExtractor.java

public static void main(String[] args) throws IOException {
    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option inputOpt = obuilder.withLongName("dir").withRequired(true)
            .withArgument(abuilder.withName("dir").withMinimum(1).withMaximum(1).create())
            .withDescription("The Lucene directory").withShortName("d").create();

    Option outputOpt = obuilder.withLongName("output").withRequired(false)
            .withArgument(abuilder.withName("output").withMinimum(1).withMaximum(1).create())
            .withDescription("The output directory").withShortName("o").create();

    Option maxOpt = obuilder.withLongName("max").withRequired(false)
            .withArgument(abuilder.withName("max").withMinimum(1).withMaximum(1).create())
            .withDescription(/*from www. j a v  a  2s  .  com*/
                    "The maximum number of vectors to output.  If not specified, then it will loop over all docs")
            .withShortName("m").create();

    Option fieldOpt = obuilder.withLongName("field").withRequired(true)
            .withArgument(abuilder.withName("field").withMinimum(1).withMaximum(1).create())
            .withDescription("The field in the index").withShortName("f").create();

    Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
            .create();

    Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(outputOpt).withOption(maxOpt)
            .withOption(fieldOpt).create();

    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        CommandLine cmdLine = parser.parse(args);

        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        File file = new File(cmdLine.getValue(inputOpt).toString());

        if (!file.isDirectory()) {
            throw new IllegalArgumentException(file + " does not exist or is not a directory");
        }

        long maxDocs = Long.MAX_VALUE;
        if (cmdLine.hasOption(maxOpt)) {
            maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString());
        }

        if (maxDocs < 0) {
            throw new IllegalArgumentException("maxDocs must be >= 0");
        }

        String field = cmdLine.getValue(fieldOpt).toString();

        PrintWriter out = null;
        if (cmdLine.hasOption(outputOpt)) {
            out = new PrintWriter(new FileWriter(cmdLine.getValue(outputOpt).toString()));
        } else {
            out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"));
        }

        File output = new File("/home/drew/taming-text/delicious/training");
        output.mkdirs();

        emitTextForTags(file, output);

        IOUtils.close(Collections.singleton(out));
    } catch (OptionException e) {
        log.error("Exception", e);
        CommandLineUtil.printHelp(group);
    }

}

From source file:com.tamingtext.tagging.LuceneCategoryExtractor.java

public static void main(String[] args) throws IOException {
    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option inputOpt = obuilder.withLongName("dir").withRequired(true)
            .withArgument(abuilder.withName("dir").withMinimum(1).withMaximum(1).create())
            .withDescription("The Lucene directory").withShortName("d").create();

    Option outputOpt = obuilder.withLongName("output").withRequired(false)
            .withArgument(abuilder.withName("output").withMinimum(1).withMaximum(1).create())
            .withDescription("The output directory").withShortName("o").create();

    Option maxOpt = obuilder.withLongName("max").withRequired(false)
            .withArgument(abuilder.withName("max").withMinimum(1).withMaximum(1).create())
            .withDescription(/*from  w  w  w  .  j  a v  a2 s. co  m*/
                    "The maximum number of documents to analyze.  If not specified, then it will loop over all docs")
            .withShortName("m").create();

    Option fieldOpt = obuilder.withLongName("field").withRequired(true)
            .withArgument(abuilder.withName("field").withMinimum(1).withMaximum(1).create())
            .withDescription("The field in the index").withShortName("f").create();

    Option helpOpt = obuilder.withLongName("help").withDescription("Print out help").withShortName("h")
            .create();

    Group group = gbuilder.withName("Options").withOption(inputOpt).withOption(outputOpt).withOption(maxOpt)
            .withOption(fieldOpt).create();

    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        CommandLine cmdLine = parser.parse(args);

        if (cmdLine.hasOption(helpOpt)) {
            CommandLineUtil.printHelp(group);
            return;
        }

        File inputDir = new File(cmdLine.getValue(inputOpt).toString());

        if (!inputDir.isDirectory()) {
            throw new IllegalArgumentException(inputDir + " does not exist or is not a directory");
        }

        long maxDocs = Long.MAX_VALUE;
        if (cmdLine.hasOption(maxOpt)) {
            maxDocs = Long.parseLong(cmdLine.getValue(maxOpt).toString());
        }

        if (maxDocs < 0) {
            throw new IllegalArgumentException("maxDocs must be >= 0");
        }

        String field = cmdLine.getValue(fieldOpt).toString();

        PrintWriter out = null;
        if (cmdLine.hasOption(outputOpt)) {
            out = new PrintWriter(new FileWriter(cmdLine.getValue(outputOpt).toString()));
        } else {
            out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"));
        }

        dumpDocumentFields(inputDir, field, maxDocs, out);

        IOUtils.close(Collections.singleton(out));
    } catch (OptionException e) {
        log.error("Exception", e);
        CommandLineUtil.printHelp(group);
    }

}

From source file:com.act.lcms.MassCalculator2.java

public static void main(String[] args) throws Exception {
    CommandLine cl = CLI_UTIL.parseCommandLine(args);

    if (cl.hasOption(OPTION_LICENSE_FILE)) {
        LOGGER.info("Using license file at %s", cl.getOptionValue(OPTION_LICENSE_FILE));
        LicenseManager.setLicenseFile(cl.getOptionValue(OPTION_LICENSE_FILE));
    }/*from  w  w  w .  j  av  a2  s  . c o  m*/

    List<String> inchis = new ArrayList<>();

    if (cl.hasOption(OPTION_INPUT_FILE)) {
        try (BufferedReader reader = new BufferedReader(new FileReader(cl.getOptionValue(OPTION_INPUT_FILE)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                inchis.add(line);
            }
        }
    }

    if (cl.getArgList().size() > 0) {
        LOGGER.info("Reading %d InChIs from the command line", cl.getArgList().size());
        inchis.addAll(cl.getArgList());
    }

    try (PrintWriter writer = new PrintWriter(
            cl.hasOption(OPTION_OUTPUT_FILE) ? new FileWriter(cl.getOptionValue(OPTION_OUTPUT_FILE))
                    : new OutputStreamWriter(System.out))) {
        writer.format("InChI\tMass\tCharge\n");

        for (String inchi : inchis) {
            try {
                Pair<Double, Integer> massAndCharge = calculateMassAndCharge(inchi);
                writer.format("%s\t%.6f\t%3d\n", inchi, massAndCharge.getLeft(), massAndCharge.getRight());
            } catch (MolFormatException e) {
                LOGGER.error("Unable to compute mass for %s: %s", inchi, e.getMessage());
            }
        }
    }
}

From source file:KnowledgeBooksNlpGenerateRdfPropertiesFromWebPages.java

public static void main(String[] args) throws Exception {
    new KnowledgeBooksNlpGenerateRdfPropertiesFromWebPages("testdata/websites.txt",
            new PrintWriter("tempdata/gen_rdf.nt"));
}

From source file:EntityToD2RHelpers.java

public static void main(String[] args) throws Exception {
    List<String> people = new ArrayList<String>();
    people.add("Mark Watson");
    List<String> places = new ArrayList<String>();
    places.add("Sedona");
    new EntityToD2RHelpers("http://example.com", "testdata/databaseinfo.txt", people, places,
            new PrintWriter("testdata/gen_rdf.nt"));
    //new EntityToD2RHelpers("http://example.com", "testdata/databaseinfo.txt", people, places, new PrintWriter(System.out));
}

From source file:io.werval.cli.DamnSmallDevShell.java

public static void main(String[] args) {
    Options options = declareOptions();/*from w w w .  j  a v  a2s  . co  m*/

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        // Handle --help
        if (cmd.hasOption("help")) {
            PrintWriter out = new PrintWriter(System.out);
            printHelp(options, out);
            out.flush();
            System.exit(0);
        }

        // Handle --version
        if (cmd.hasOption("version")) {
            System.out.print(String.format(
                    "Werval CLI v%s\n" + "Git commit: %s%s, built on: %s\n" + "Java version: %s, vendor: %s\n"
                            + "Java home: %s\n" + "Default locale: %s, platform encoding: %s\n"
                            + "OS name: %s, version: %s, arch: %s\n",
                    VERSION, COMMIT, (DIRTY ? " (DIRTY)" : ""), DATE, System.getProperty("java.version"),
                    System.getProperty("java.vendor"), System.getProperty("java.home"),
                    Locale.getDefault().toString(), System.getProperty("file.encoding"),
                    System.getProperty("os.name"), System.getProperty("os.version"),
                    System.getProperty("os.arch")));
            System.out.flush();
            System.exit(0);
        }

        // Debug
        final boolean debug = cmd.hasOption('d');

        // Temporary directory
        final File tmpDir = new File(cmd.getOptionValue('t', "build" + separator + "devshell.tmp"));
        if (debug) {
            System.out.println("Temporary directory set to '" + tmpDir.getAbsolutePath() + "'.");
        }

        // Handle commands
        @SuppressWarnings("unchecked")
        List<String> commands = cmd.getArgList();
        if (commands.isEmpty()) {
            commands = Collections.singletonList("start");
        }
        if (debug) {
            System.out.println("Commands to be executed: " + commands);
        }
        Iterator<String> commandsIterator = commands.iterator();
        while (commandsIterator.hasNext()) {
            String command = commandsIterator.next();
            switch (command) {
            case "new":
                System.out.println(LOGO);
                newCommand(commandsIterator.hasNext() ? commandsIterator.next() : "werval-application", cmd);
                break;
            case "clean":
                cleanCommand(debug, tmpDir);
                break;
            case "devshell":
                System.out.println(LOGO);
                devshellCommand(debug, tmpDir, cmd);
                break;
            case "start":
                System.out.println(LOGO);
                startCommand(debug, tmpDir, cmd);
                break;
            case "secret":
                secretCommand();
                break;
            default:
                PrintWriter out = new PrintWriter(System.err);
                System.err.println("Unknown command: '" + command + "'");
                printHelp(options, out);
                out.flush();
                System.exit(1);
                break;
            }
        }
    } catch (IllegalArgumentException | ParseException | IOException ex) {
        PrintWriter out = new PrintWriter(System.err);
        printHelp(options, out);
        out.flush();
        System.exit(1);
    } catch (WervalException ex) {
        ex.printStackTrace(System.err);
        System.err.flush();
        System.exit(1);
    }
}

From source file:org.jfree.chart.demo.ImageMapDemo2.java

/**
 * The starting point for the demo.//from  w  w w  .  ja  v a  2s  .c  o m
 *
 * @param args  ignored.
 */
public static void main(final String[] args) {

    // create a chart
    final DefaultPieDataset data = new DefaultPieDataset();
    data.setValue("One", new Double(43.2));
    data.setValue("Two", new Double(10.0));
    data.setValue("Three", new Double(27.5));
    data.setValue("Four", new Double(17.5));
    data.setValue("Five", new Double(11.0));
    data.setValue("Six", new Double(19.4));

    JFreeChart chart = null;
    final boolean drilldown = true;

    // create the chart...
    if (drilldown) {
        final PiePlot plot = new PiePlot(data);
        //          plot.setInsets(new Insets(0, 5, 5, 5));
        plot.setToolTipGenerator(new StandardPieItemLabelGenerator());
        plot.setURLGenerator(new StandardPieURLGenerator("pie_chart_detail.jsp"));
        chart = new JFreeChart("Pie Chart Demo 1", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    } else {
        chart = ChartFactory.createPieChart("Pie Chart Demo 1", // chart title
                data, // data
                true, // include legend
                true, 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("piechart100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("piechart100.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 2</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"piechart100.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());
    }

}

From source file:com.archivas.clienttools.arcmover.cli.ArcJobMgr.java

@SuppressWarnings({ "UseOfSystemOutOrSystemErr" })
public static void main(String args[]) {
    ArcJobMgr arcJobMgr = null;/*from  w w w. jav  a 2s .c om*/

    ConfigurationHelper.validateLaunchOK();

    try {
        arcJobMgr = new ArcJobMgr(args);
        arcJobMgr.parseArgs();
        if (cmdAction == JobMgrAction.HELP) {
            System.out.println(arcJobMgr.helpScreen());
        } else {
            arcJobMgr.execute(new PrintWriter(System.out), new PrintWriter(System.err));
        }
    } catch (ParseException e) {
        System.out.println("Error: " + e.getMessage());
        System.out.println();
        System.out.println(arcJobMgr.helpScreen());
        arcJobMgr.setExitCode(EXIT_CODE_OPTION_PARSE_ERROR);
    } catch (Exception e) {
        LOG.log(Level.SEVERE, "Unexpected Exception.", e);
        System.out.println();
        System.out.println("Failed to create a new profile " + e.getMessage());
        arcJobMgr.setExitCode(EXIT_CODE_DM_ERROR);
    } finally {
        if (arcJobMgr != null) {
            arcJobMgr.exit();
        }
    }
}