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:Main.java

public static void error(Component parent, Exception e, String title) {
    StringWriter out = new StringWriter();
    e.printStackTrace(new PrintWriter(out));
    out.flush();// ww  w .j a va  2 s . c om
    error(parent, out.getBuffer().toString(), title);
}

From source file:Main.java

public static void writeXML(Document d, OutputStream os, String sysID) throws IOException {
    /**//from   ww  w  .  j a  v  a2 s  .  c  o  m
     * To support i18n, we have to specify the encoding of
     * output writer to UTF-8 when we writing the XML.
     */
    // PrintWriter out=new PrintWriter(os);
    PrintWriter out = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));

    out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    out.println();
    if (sysID != null) {
        out.println("<!DOCTYPE " + d.getDoctype().getName() + " SYSTEM \"" + sysID + "\">");
        out.println();
    }
    //d.getDocumentElement().normalize();
    writeXMLwalkTree(d.getDocumentElement(), 0, out);
    out.flush();
}

From source file:Main.java

public static void putString2XmlFile(String xml, String fileName) {
    PrintWriter out = null;//w ww  . j a va2s .  c  o  m
    try {
        out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
        out.write(xml, 0, xml.length());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        out.flush();
        out.close();
    }
}

From source file:Main.java

/**
 * dump bipartite community affiliation into a text file with node names
 * /*from w  ww  .j  a va 2 s .c o m*/
 * @param OutFNm
 * @param CmtyVV
 * @param NIDNmH
 */
static void dumpCmtyVV(final String OutFNm, Vector<Vector<Integer>> CmtyVV, Hashtable<Integer, String> NIDNmH) {
    PrintWriter f;
    try {
        f = new PrintWriter(OutFNm);

        for (int c = 0; c < CmtyVV.size(); c++) {
            for (int u = 0; u < CmtyVV.get(c).size(); u++) {
                if (NIDNmH.containsKey(CmtyVV.get(c).get(u))) {
                    f.printf("%s\t", NIDNmH.get(CmtyVV.get(c).get(u)));
                } else {
                    f.printf("%d\t", (int) CmtyVV.get(c).get(u));
                }
            }
            f.printf("\n");
        }
        f.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

public static void premain(final Instrumentation inst) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                PrintWriter out = new PrintWriter(System.err);

                ThreadMXBean tb = ManagementFactory.getThreadMXBean();
                out.printf("Current thread count: %d%n", tb.getThreadCount());
                out.printf("Peak thread count: %d%n", tb.getPeakThreadCount());

                List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
                for (MemoryPoolMXBean pool : pools) {
                    MemoryUsage peak = pool.getPeakUsage();
                    out.printf("Peak %s memory used: %,d%n", pool.getName(), peak.getUsed());
                    out.printf("Peak %s memory reserved: %,d%n", pool.getName(), peak.getCommitted());
                }//from w  w w .j a va 2  s.co  m

                Class[] loaded = inst.getAllLoadedClasses();
                out.println("Loaded classes:");
                for (Class c : loaded)
                    out.println(c.getName());
                out.close();
            } catch (Throwable t) {
                System.err.println("Exception in agent: " + t);
            }
        }
    });
}

From source file:Main.java

/**
 * Write a string to a file/*from ww w. j a v  a2s.  c o m*/
 *  @param content The string to write out
 *  @param outputfile The file to which the string will be written
 */
public static void writeStringToFile(String content, File outputfile) {
    if (content != null && !content.equals("") && outputfile != null) {
        try {
            PrintWriter pwriter = new PrintWriter(new FileWriter(outputfile));
            pwriter.print(content);
            pwriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:json_to_xml_1.java

public static void main(String args[]) {
    System.out.print("json_to_xml_1 workflow Copyright (C) 2016 Stephan Kreutzer\n"
            + "This program comes with ABSOLUTELY NO WARRANTY.\n"
            + "This is free software, and you are welcome to redistribute it\n"
            + "under certain conditions. See the GNU Affero General Public License 3\n"
            + "or any later version for details. Also, see the source code repository\n"
            + "https://github.com/publishing-systems/digital_publishing_workflow_tools/ and\n"
            + "the project website http://www.publishing-systems.org.\n\n");

    json_to_xml_1 converter = json_to_xml_1.getInstance();

    converter.getInfoMessages().clear();

    try {//w w w . j av  a2s.c o  m
        converter.execute(args);
    } catch (ProgramTerminationException ex) {
        converter.handleTermination(ex);
    }

    if (converter.resultInfoFile != null) {
        try {
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(converter.resultInfoFile), "UTF-8"));

            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            writer.write(
                    "<!-- This file was created by json_to_xml_1, which is free software licensed under the GNU Affero General Public License 3 or any later version (see https://github.com/publishing-systems/digital_publishing_workflow_tools/ and http://www.publishing-systems.org). -->\n");
            writer.write("<json-to-xml-1-result-information>\n");

            if (converter.getInfoMessages().size() <= 0) {
                writer.write("  <success/>\n");
            } else {
                writer.write("  <success>\n");
                writer.write("    <info-messages>\n");

                for (int i = 0, max = converter.getInfoMessages().size(); i < max; i++) {
                    InfoMessage infoMessage = converter.getInfoMessages().get(i);

                    writer.write("      <info-message number=\"" + i + "\">\n");
                    writer.write("        <timestamp>" + infoMessage.getTimestamp() + "</timestamp>\n");

                    String infoMessageText = infoMessage.getMessage();
                    String infoMessageId = infoMessage.getId();
                    String infoMessageBundle = infoMessage.getBundle();
                    Object[] infoMessageArguments = infoMessage.getArguments();

                    if (infoMessageBundle != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageBundle = infoMessageBundle.replaceAll("&", "&amp;");
                        infoMessageBundle = infoMessageBundle.replaceAll("<", "&lt;");
                        infoMessageBundle = infoMessageBundle.replaceAll(">", "&gt;");

                        writer.write("        <id-bundle>" + infoMessageBundle + "</id-bundle>\n");
                    }

                    if (infoMessageId != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageId = infoMessageId.replaceAll("&", "&amp;");
                        infoMessageId = infoMessageId.replaceAll("<", "&lt;");
                        infoMessageId = infoMessageId.replaceAll(">", "&gt;");

                        writer.write("        <id>" + infoMessageId + "</id>\n");
                    }

                    if (infoMessageText != null) {
                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        infoMessageText = infoMessageText.replaceAll("&", "&amp;");
                        infoMessageText = infoMessageText.replaceAll("<", "&lt;");
                        infoMessageText = infoMessageText.replaceAll(">", "&gt;");

                        writer.write("        <message>" + infoMessageText + "</message>\n");
                    }

                    if (infoMessageArguments != null) {
                        writer.write("        <arguments>\n");

                        int argumentCount = infoMessageArguments.length;

                        for (int j = 0; j < argumentCount; j++) {
                            if (infoMessageArguments[j] == null) {
                                writer.write("          <argument number=\"" + j + "\">\n");
                                writer.write("            <class></class>\n");
                                writer.write("            <value>null</value>\n");
                                writer.write("          </argument>\n");

                                continue;
                            }

                            String className = infoMessageArguments[j].getClass().getName();

                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            className = className.replaceAll("&", "&amp;");
                            className = className.replaceAll("<", "&lt;");
                            className = className.replaceAll(">", "&gt;");

                            String value = infoMessageArguments[j].toString();

                            // Ampersand needs to be the first, otherwise it would double-encode
                            // other entities.
                            value = value.replaceAll("&", "&amp;");
                            value = value.replaceAll("<", "&lt;");
                            value = value.replaceAll(">", "&gt;");

                            writer.write("          <argument number=\"" + j + "\">\n");
                            writer.write("            <class>" + className + "</class>\n");
                            writer.write("            <value>" + value + "</value>\n");
                            writer.write("          </argument>\n");
                        }

                        writer.write("        </arguments>\n");
                    }

                    Exception exception = infoMessage.getException();

                    if (exception != null) {
                        writer.write("        <exception>\n");

                        String className = exception.getClass().getName();

                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        className = className.replaceAll("&", "&amp;");
                        className = className.replaceAll("<", "&lt;");
                        className = className.replaceAll(">", "&gt;");

                        writer.write("          <class>" + className + "</class>\n");

                        StringWriter stringWriter = new StringWriter();
                        PrintWriter printWriter = new PrintWriter(stringWriter);
                        exception.printStackTrace(printWriter);
                        String stackTrace = stringWriter.toString();

                        // Ampersand needs to be the first, otherwise it would double-encode
                        // other entities.
                        stackTrace = stackTrace.replaceAll("&", "&amp;");
                        stackTrace = stackTrace.replaceAll("<", "&lt;");
                        stackTrace = stackTrace.replaceAll(">", "&gt;");

                        writer.write("          <stack-trace>" + stackTrace + "</stack-trace>\n");
                        writer.write("        </exception>\n");
                    }

                    writer.write("      </info-message>\n");
                }

                writer.write("    </info-messages>\n");
                writer.write("  </success>\n");
            }

            writer.write("</json-to-xml-1-result-information>\n");
            writer.flush();
            writer.close();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            System.exit(-1);
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
            System.exit(-1);
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(-1);
        }
    }

    converter.getInfoMessages().clear();
    converter.resultInfoFile = null;
}

From source file:edu.msu.cme.rdp.seqmatch.cli.SeqmatchCheckRevSeq.java

public static void main(String[] args) throws Exception {

    String trainingFile = null;//  w w w  . java 2  s. com
    String queryFile = null;
    String outputFile = null;
    PrintWriter revOutputWriter = new PrintWriter(System.out);
    PrintStream correctedQueryOut = System.out;
    String traineeDesc = null;
    int numOfResults = 20;
    boolean checkReverse = false;

    float diffScoreCutoff = CheckReverseSeq.DIFF_SCORE_CUTOFF;
    String format = "txt"; // default

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

        if (line.hasOption("c")) {
            checkReverse = true;
        }

        if (line.hasOption("t")) {
            trainingFile = line.getOptionValue("t");
        } else {
            throw new Exception("training file must be specified");
        }
        if (line.hasOption("q")) {
            queryFile = line.getOptionValue("q");
        } else {
            throw new Exception("query file must be specified");
        }
        if (line.hasOption("o")) {
            outputFile = line.getOptionValue("o");
        } else {
            throw new Exception("output file must be specified");
        }
        if (line.hasOption("r")) {
            revOutputWriter = new PrintWriter(line.getOptionValue("r"));
        }
        if (line.hasOption("s")) {
            correctedQueryOut = new PrintStream(line.getOptionValue("s"));
        }
        if (line.hasOption("d")) {
            diffScoreCutoff = Float.parseFloat(line.getOptionValue("d"));
        }
        if (line.hasOption("h")) {
            traineeDesc = line.getOptionValue("h");
        }
        if (line.hasOption("n")) {
            numOfResults = Integer.parseInt(line.getOptionValue("n"));
        }
        if (line.hasOption("f")) {
            format = line.getOptionValue("f");
            if (!format.equals("tab") && !format.equals("dbformat") && !format.equals("xml")) {
                throw new IllegalArgumentException("Only dbformat, tab or xml format available");
            }
        }

    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(120, "SeqmatchCheckRevSeq", "", options, "", true);
        return;
    }

    SeqmatchCheckRevSeq theObj = new SeqmatchCheckRevSeq();

    if (!checkReverse) {
        theObj.doUserLibMatch(queryFile, trainingFile, outputFile, numOfResults, format, traineeDesc);
    } else {
        theObj.checkRevSeq(queryFile, trainingFile, outputFile, revOutputWriter, correctedQueryOut,
                diffScoreCutoff, format, traineeDesc);
    }
}

From source file:Main.java

private static String stringForm(Throwable e) {
    StringWriter sw = new StringWriter(256);
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);//from  ww  w.j  a v a 2 s. com
    return sw.getBuffer().toString();
}

From source file:com.bstek.dorado.idesupport.StandaloneRuleSetExporter.java

public static void main(String[] args) throws Exception {
    String ruleSetFile = null;/*from ww w  .  j  a v a  2 s  .  co m*/
    String doradoHome = null;
    if (args.length >= 2) {
        ruleSetFile = args[0];
        doradoHome = args[1];
    } else {
        throw new IllegalArgumentException();
    }

    if (StringUtils.isEmpty(doradoHome)) {
        doradoHome = System.getenv("DORADO_HOME");
    }

    StandaloneRuleSetExporter instance = new StandaloneRuleSetExporter(doradoHome);

    FileOutputStream fos = new FileOutputStream(ruleSetFile);
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(fos, Constants.DEFAULT_CHARSET));
    try {
        instance.exportRuleSet(writer);
    } finally {
        writer.flush();
        writer.close();
        fos.close();
    }
}