Example usage for java.io PrintWriter write

List of usage examples for java.io PrintWriter write

Introduction

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

Prototype

public void write(String s) 

Source Link

Document

Writes a string.

Usage

From source file:DataCrawler.OpenAIRE.XMLGenerator.java

public static void main(String[] args) {
    String text = "";

    try {//  w  ww  .  ja  va2 s . com
        if (args.length < 4) {
            System.out.println("<command> template_file csv_file output_dir log_file [start_id]");
        }

        // InputStream fis = new FileInputStream("E:/Downloads/result-r-00000");
        InputStream fis = new FileInputStream(args[1]);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));

        // String content = new String(Files.readAllBytes(Paths.get("publications_template.xml")));
        String content = new String(Files.readAllBytes(Paths.get(args[0])));
        Document doc = Jsoup.parse(content, "UTF-8", Parser.xmlParser());
        // String outputDirectory = "G:/";
        String outputDirectory = args[2];
        // PrintWriter logWriter = new PrintWriter(new FileOutputStream("publication.log",false));
        PrintWriter logWriter = new PrintWriter(new FileOutputStream(args[3], false));
        Element objectId = null, title = null, publisher = null, dateofacceptance = null, bestlicense = null,
                resulttype = null, originalId = null, originalId2 = null;
        boolean start = true;
        // String startID = "dedup_wf_001::207a098867b64f3b5af505fa3aeecd24";
        String startID = "";
        if (args.length >= 5) {
            start = false;
            startID = args[4];
        }
        String previousText = "";
        while ((text = br.readLine()) != null) {
            /*  For publications:
                0. dri:objIdentifier context
               9. title context
               12. publisher context
               18. dateofacceptance
               19. bestlicense @classname
               21. resulttype  @classname
               26. originalId context  
               (Notice that the prefix is null and will use space to separate two different "originalId")
            */

            if (!previousText.isEmpty()) {
                text = previousText + text;
                start = true;
                previousText = "";
            }

            String[] items = text.split("!");
            for (int i = 0; i < items.length; ++i) {
                items[i] = StringUtils.strip(items[i], "#");
            }
            if (objectId == null)
                objectId = doc.getElementsByTag("dri:objIdentifier").first();
            objectId.text(items[0]);

            if (!start && items[0].equals(startID)) {
                start = true;
            }

            if (title == null)
                title = doc.getElementsByTag("title").first();
            title.text(items[9]);

            if (publisher == null)
                publisher = doc.getElementsByTag("publisher").first();

            if (items.length < 12) {
                previousText = text;
                continue;
            }
            publisher.text(items[12]);

            if (dateofacceptance == null)
                dateofacceptance = doc.getElementsByTag("dateofacceptance").first();
            dateofacceptance.text(items[18]);

            if (bestlicense == null)
                bestlicense = doc.getElementsByTag("bestlicense").first();
            bestlicense.attr("classname", items[19]);

            if (resulttype == null)
                resulttype = doc.getElementsByTag("resulttype").first();
            resulttype.attr("classname", items[21]);

            if (originalId == null || originalId2 == null) {
                Elements elements = doc.getElementsByTag("originalId");
                String[] context = items[26].split(" ");
                if (elements.size() > 0) {
                    if (elements.size() >= 1) {
                        originalId = elements.get(0);
                        if (context.length >= 1) {
                            int indexOfnull = context[0].trim().indexOf("null");
                            String value = "";
                            if (indexOfnull != -1) {
                                if (context[0].trim().length() >= (indexOfnull + 5))
                                    value = context[0].trim().substring(indexOfnull + 5);

                            } else {
                                value = context[0].trim();
                            }
                            originalId.text(value);
                        }
                    }
                    if (elements.size() >= 2) {
                        originalId2 = elements.get(1);
                        if (context.length >= 2) {
                            int indexOfnull = context[1].trim().indexOf("null");
                            String value = "";
                            if (indexOfnull != -1) {
                                if (context[1].trim().length() >= (indexOfnull + 5))
                                    value = context[1].trim().substring(indexOfnull + 5);

                            } else {
                                value = context[1].trim();
                            }
                            originalId2.text(value);
                        }
                    }
                }
            } else {
                String[] context = items[26].split(" ");
                if (context.length >= 1) {
                    int indexOfnull = context[0].trim().indexOf("null");
                    String value = "";
                    if (indexOfnull != -1) {
                        if (context[0].trim().length() >= (indexOfnull + 5))
                            value = context[0].trim().substring(indexOfnull + 5);

                    } else {
                        value = context[0].trim();
                    }
                    originalId.text(value);
                }
                if (context.length >= 2) {
                    int indexOfnull = context[1].trim().indexOf("null");
                    String value = "";
                    if (indexOfnull != -1) {
                        if (context[1].trim().length() >= (indexOfnull + 5))
                            value = context[1].trim().substring(indexOfnull + 5);

                    } else {
                        value = context[1].trim();
                    }
                    originalId2.text(value);
                }
            }
            if (start) {
                String filePath = outputDirectory + items[0].replace(":", "#") + ".xml";
                PrintWriter writer = new PrintWriter(new FileOutputStream(filePath, false));
                logWriter.write(filePath + " > Start" + System.lineSeparator());
                writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + System.lineSeparator());
                writer.write(doc.getElementsByTag("response").first().toString());
                writer.close();
                logWriter.write(filePath + " > OK" + System.lineSeparator());
                logWriter.flush();
            }

        }
        logWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.msu.cme.rdp.multicompare.Main.java

public static void main(String[] args) throws Exception {
    PrintStream hier_out = null;//  w ww . j  a  v a  2s .  c o m
    PrintWriter assign_out = new PrintWriter(new NullWriter());
    PrintStream bootstrap_out = null;
    File hier_out_filename = null;
    String propFile = null;
    File biomFile = null;
    File metadataFile = null;
    PrintWriter shortseq_out = null;
    List<MCSample> samples = new ArrayList();
    ClassificationResultFormatter.FORMAT format = ClassificationResultFormatter.FORMAT.allRank;
    float conf = CmdOptions.DEFAULT_CONF;
    String gene = null;
    int min_bootstrap_words = Classifier.MIN_BOOTSTRSP_WORDS;

    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption(CmdOptions.OUTFILE_SHORT_OPT)) {
            assign_out = new PrintWriter(line.getOptionValue(CmdOptions.OUTFILE_SHORT_OPT));
        } else {
            throw new IllegalArgumentException("Require the output file for classification assignment");
        }
        if (line.hasOption(CmdOptions.HIER_OUTFILE_SHORT_OPT)) {
            hier_out_filename = new File(line.getOptionValue(CmdOptions.HIER_OUTFILE_SHORT_OPT));
            hier_out = new PrintStream(hier_out_filename);
        }
        if (line.hasOption(CmdOptions.BIOMFILE_SHORT_OPT)) {
            biomFile = new File(line.getOptionValue(CmdOptions.BIOMFILE_SHORT_OPT));
        }
        if (line.hasOption(CmdOptions.METADATA_SHORT_OPT)) {
            metadataFile = new File(line.getOptionValue(CmdOptions.METADATA_SHORT_OPT));
        }

        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 {
                propFile = line.getOptionValue(CmdOptions.TRAINPROPFILE_SHORT_OPT);
            }
        }
        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("filterbyconf")) {
                format = ClassificationResultFormatter.FORMAT.filterbyconf;
            } else if (f.equalsIgnoreCase("db")) {
                format = ClassificationResultFormatter.FORMAT.dbformat;
            } else if (f.equalsIgnoreCase("biom")) {
                format = ClassificationResultFormatter.FORMAT.biom;
            } else {
                throw new IllegalArgumentException(
                        "Not an valid output format, only allrank, fixrank, biom, filterbyconf and db allowed");
            }
        }
        if (line.hasOption(CmdOptions.GENE_SHORT_OPT)) {
            if (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 + " not found, choose from"
                        + ClassifierFactory.RRNA_16S_GENE + ", " + ClassifierFactory.FUNGALLSU_GENE + ", "
                        + ClassifierFactory.FUNGALITS_warcup_GENE + ", "
                        + ClassifierFactory.FUNGALITS_unite_GENE);
            }
        }
        if (line.hasOption(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT)) {
            min_bootstrap_words = Integer
                    .parseInt(line.getOptionValue(CmdOptions.MIN_BOOTSTRAP_WORDS_SHORT_OPT));
            if (min_bootstrap_words < Classifier.MIN_BOOTSTRSP_WORDS) {
                throw new IllegalArgumentException(CmdOptions.MIN_BOOTSTRAP_WORDS_LONG_OPT
                        + " must be at least " + Classifier.MIN_BOOTSTRSP_WORDS);
            }
        }
        if (line.hasOption(CmdOptions.BOOTSTRAP_SHORT_OPT)) {
            String confString = line.getOptionValue(CmdOptions.BOOTSTRAP_SHORT_OPT);
            try {
                conf = Float.valueOf(confString);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("Confidence must be a decimal number");
            }

            if (conf < 0 || conf > 1) {
                throw new IllegalArgumentException("Confidence must be in the range [0,1]");
            }
        }
        if (line.hasOption(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT)) {
            shortseq_out = new PrintWriter(line.getOptionValue(CmdOptions.SHORTSEQ_OUTFILE_SHORT_OPT));
        }
        if (line.hasOption(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT)) {
            bootstrap_out = new PrintStream(line.getOptionValue(CmdOptions.BOOTSTRAP_OUTFILE_SHORT_OPT));
        }

        if (format.equals(ClassificationResultFormatter.FORMAT.biom) && biomFile == null) {
            throw new IllegalArgumentException("biom format requires an input biom file");
        }
        if (biomFile != null) { // if input biom file provided, use biom format
            format = ClassificationResultFormatter.FORMAT.biom;
        }

        args = line.getArgs();
        for (String arg : args) {
            String[] inFileNames = arg.split(",");
            File inputFile = new File(inFileNames[0]);
            File idmappingFile = null;
            if (!inputFile.exists()) {
                throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[0] + "\"");
            }
            if (inFileNames.length == 2) {
                idmappingFile = new File(inFileNames[1]);
                if (!idmappingFile.exists()) {
                    throw new IllegalArgumentException("Failed to find input file \"" + inFileNames[1] + "\"");
                }
            }

            MCSample nextSample = new MCSample(inputFile, idmappingFile);
            samples.add(nextSample);
        }
        if (propFile == null && gene == null) {
            gene = CmdOptions.DEFAULT_GENE;
        }
        if (samples.size() < 1) {
            throw new IllegalArgumentException("Require at least one sample files");
        }
    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(80, " [options] <samplefile>[,idmappingfile] ...", "", options, "");
        return;
    }

    MultiClassifier multiClassifier = new MultiClassifier(propFile, gene, biomFile, metadataFile);
    MultiClassifierResult result = multiClassifier.multiCompare(samples, conf, assign_out, format,
            min_bootstrap_words);
    assign_out.close();
    if (hier_out != null) {
        DefaultPrintVisitor printVisitor = new DefaultPrintVisitor(hier_out, samples);
        result.getRoot().topDownVisit(printVisitor);
        hier_out.close();
        if (multiClassifier.hasCopyNumber()) {
            // print copy number corrected counts
            File cn_corrected_s = new File(hier_out_filename.getParentFile(),
                    "cnadjusted_" + hier_out_filename.getName());
            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();
        }
    }

    if (bootstrap_out != null) {
        for (MCSample sample : samples) {
            MCSamplePrintUtil.printBootstrapCountTable(bootstrap_out, sample);
        }
        bootstrap_out.close();
    }

    if (shortseq_out != null) {
        for (String id : result.getBadSequences()) {
            shortseq_out.write(id + "\n");
        }
        shortseq_out.close();
    }

}

From source file:Main.java

private static void writeFile(String filePath, String content) throws IOException {
    FileWriter fw = new FileWriter(filePath);
    PrintWriter out = new PrintWriter(fw);
    out.write(content);
    out.println();//from  ww  w .  j a  v  a 2s.c  om
    fw.close();
    out.close();
}

From source file:de.tudarmstadt.ukp.dkpro.c4corpus.boilerplate.standalone.HTMLBoilerplateRemoval.java

public static void processHtmlFile(File input, File outFile, boolean keepMinimalHtml) throws IOException {
    // read the html file
    String html = FileUtils.readFileToString(input, "utf-8");

    // boilerplate removal
    String cleanText;//from   ww  w.ja v  a 2  s . co  m
    if (keepMinimalHtml) {
        cleanText = boilerPlateRemoval.getMinimalHtml(html, null);
    } else {
        cleanText = boilerPlateRemoval.getPlainText(html, null);
    }

    // write to the output file
    PrintWriter writer = new PrintWriter(outFile, "utf-8");
    writer.write(cleanText);

    writer.close();
}

From source file:de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.statistics.StatisticsTableCreator.java

public static void saveTableToCsv(Table<String, String, Long> table, OutputStream outputStream) {
    PrintWriter pw = new PrintWriter(outputStream);
    pw.write(";");
    for (String columnKey : table.columnKeySet()) {
        pw.printf("%s;", columnKey);
    }//from w w  w.j  av  a2 s.c o  m
    pw.println();

    for (String rowKey : table.rowKeySet()) {
        pw.printf("%s;", rowKey);
        for (String columnKey : table.columnKeySet()) {
            Long value = table.get(rowKey, columnKey);
            pw.printf("%d;", value != null ? value : 0);
        }
        pw.println();
    }

    IOUtils.closeQuietly(pw);
}

From source file:com.yolodata.tbana.testutils.FileTestUtils.java

public static boolean createFileWithContent(String filepath, String content) throws IOException {
    File f = new File(filepath);
    if (!f.createNewFile())
        return false;

    PrintWriter pw = new PrintWriter(f);
    pw.write(content);
    pw.close();/*  www  . j  av a 2 s .  co m*/

    return true;
}

From source file:com.arsdigita.util.parameter.ParameterPrinter.java

private static void writeRecord(final ParameterContext record, final PrintWriter out) {
    out.write("<record>");

    final Parameter[] params = record.getParameters();

    for (int i = 0; i < params.length; i++) {
        writeParameter(params[i], out);/*from  w w w.ja  v a2  s . c  om*/
    }

    out.write("</record>");
}

From source file:com.arsdigita.util.parameter.ParameterPrinter.java

private static void writeXML(final PrintWriter out) {
    out.write("<?xml version=\"1.0\"?>");
    out.write("<records>");

    final Iterator records = s_records.iterator();

    while (records.hasNext()) {
        writeRecord(((ParameterContext) records.next()), out);
    }// w w w  .  ja  v  a 2 s.  c  om

    out.write("</records>");
    out.close();
}

From source file:com.arsdigita.util.parameter.ParameterPrinter.java

private static void writeParameter(final Parameter param, final PrintWriter out) {
    out.write("<parameter>");

    field(out, "name", param.getName());

    if (param.isRequired()) {
        out.write("<required/>");
    }/*from   w  w  w  .  ja v a 2 s. c o m*/

    final ParameterInfo info = param.getInfo();

    if (info != null) {
        field(out, "title", info.getTitle());
        field(out, "purpose", info.getPurpose());
        field(out, "example", info.getExample());
        field(out, "format", info.getFormat());
    }

    out.write("</parameter>");
}

From source file:de.ocarthon.core.utility.GzipCompression.java

public static void compress(String input, OutputStream os) throws IOException {
    GZIPOutputStream gos = null;/*from ww w.  ja va2s  .  com*/
    PrintWriter pw = null;

    try {
        gos = new GZIPOutputStream(os);
        pw = new PrintWriter(gos);
        pw.write(input);
    } finally {
        IOUtils.closeQuietly(pw);
        IOUtils.closeQuietly(gos);
    }
}