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

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

From source file:edu.usf.cutr.obascs.io.FileUtil.java

public static void writeToFile(String text, String path) throws FileNotFoundException {
    File file = new File(path);
    PrintWriter printWriter = new PrintWriter(file);
    printWriter.println(text);//from  w  w w .  j a  v  a  2  s .  co m
    printWriter.close();
}

From source file:Main.java

public static void saveToFile(File folder, String name, String data) {

    File file = new File(folder, name);

    PrintWriter pw = null;/*from   ww w.j a v a2 s.  c o  m*/
    try {
        Writer w = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        pw = new PrintWriter(w);
        pw.write(data);

    } catch (IOException e) {
        Log.e(TAG, e.getMessage(), e);
    } finally {
        if (pw != null) {
            pw.close();
        }
    }
}

From source file:Main.java

public static void xmlToFile(Document doc, String fileNameToWrite) throws Exception {
    DOMSource domSource = new DOMSource(doc);
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileNameToWrite)));
    StreamResult streamResult = new StreamResult(out);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.transform(domSource, streamResult);
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step6HITPreparator.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // step5-linguistic-annotation/
    System.err.println("Starting step 6 HIT Preparation");

    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (outputDir.exists()) {
        outputDir.delete();/*from  w w  w. j  a va 2 s.  c  o m*/
    }
    outputDir.mkdir();

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

    // iterate over query containers
    int countClueWeb = 0;
    int countSentence = 0;
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        if (queries.contains(f.getName()) || queries.size() == 0) {
            // groups contain only non-empty documents
            Map<Integer, List<QueryResultContainer.SingleRankedResult>> groups = new HashMap<>();

            // split to groups according to number of sentences
            for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) {
                if (rankedResult.originalXmi != null) {
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));
                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    Collection<Sentence> sentences = JCasUtil.select(jCas, Sentence.class);

                    int groupId = sentences.size() / 40;
                    if (rankedResult.originalXmi == null) {
                        System.err.println("Empty document: " + rankedResult.clueWebID);
                    } else {
                        if (!groups.containsKey(groupId)) {
                            groups.put(groupId, new ArrayList<>());

                        }
                    }
                    //handle it
                    groups.get(groupId).add(rankedResult);
                    countClueWeb++;
                }
            }

            for (Map.Entry<Integer, List<QueryResultContainer.SingleRankedResult>> entry : groups.entrySet()) {
                Integer groupId = entry.getKey();
                List<QueryResultContainer.SingleRankedResult> rankedResults = entry.getValue();

                // make sure the results are sorted
                // DEBUG
                //                for (QueryResultContainer.SingleRankedResult r : rankedResults) {
                //                    System.out.print(r.rank + "\t");
                //                }

                Collections.sort(rankedResults, (o1, o2) -> o1.rank.compareTo(o2.rank));

                // iterate over results for one query and group
                for (int i = 0; i < rankedResults.size() && i < TOP_RESULTS_PER_GROUP; i++) {
                    QueryResultContainer.SingleRankedResult rankedResult = rankedResults.get(i);

                    QueryResultContainer.SingleRankedResult r = rankedResults.get(i);
                    int rank = r.rank;
                    MustacheFactory mf = new DefaultMustacheFactory();
                    Mustache mustache = mf.compile("template/template.html");
                    String queryId = queryResultContainer.qID;
                    String query = queryResultContainer.query;
                    // make the first letter uppercase
                    query = query.substring(0, 1).toUpperCase() + query.substring(1);

                    List<String> relevantInformationExamples = queryResultContainer.relevantInformationExamples;
                    List<String> irrelevantInformationExamples = queryResultContainer.irrelevantInformationExamples;
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));

                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    List<generators.Sentence> sentences = new ArrayList<>();
                    List<Integer> paragraphs = new ArrayList<>();
                    paragraphs.add(0);

                    for (WebParagraph webParagraph : JCasUtil.select(jCas, WebParagraph.class)) {
                        for (Sentence s : JCasUtil.selectCovered(Sentence.class, webParagraph)) {

                            String sentenceBegin = String.valueOf(s.getBegin());
                            generators.Sentence sentence = new generators.Sentence(s.getCoveredText(),
                                    sentenceBegin);
                            sentences.add(sentence);
                            countSentence++;
                        }
                        int SentenceID = paragraphs.get(paragraphs.size() - 1);
                        if (sentences.size() > 120)
                            while (SentenceID < sentences.size()) {
                                if (!paragraphs.contains(SentenceID))
                                    paragraphs.add(SentenceID);
                                SentenceID = SentenceID + 120;
                            }
                        paragraphs.add(sentences.size());

                    }
                    System.err.println("Output dir: " + outputDir);
                    int startID = 0;
                    int endID;

                    for (int j = 0; j < paragraphs.size(); j++) {

                        endID = paragraphs.get(j);
                        int sentLength = endID - startID;
                        if (sentLength > 120 || j == paragraphs.size() - 1) {
                            if (sentLength > 120) {

                                endID = paragraphs.get(j - 1);
                                j--;
                            }
                            sentLength = endID - startID;
                            if (sentLength <= 40)
                                groupId = 40;
                            else if (sentLength <= 80 && sentLength > 40)
                                groupId = 80;
                            else if (sentLength > 80)
                                groupId = 120;

                            File folder = new File(outputDir + "/" + groupId);
                            if (!folder.exists()) {
                                System.err.println("creating directory: " + outputDir + "/" + groupId);
                                boolean result = false;

                                try {
                                    folder.mkdir();
                                    result = true;
                                } catch (SecurityException se) {
                                    //handle it
                                }
                                if (result) {
                                    System.out.println("DIR created");
                                }
                            }

                            String newHtmlFile = folder.getAbsolutePath() + "/" + f.getName() + "_"
                                    + rankedResult.clueWebID + "_" + sentLength + ".html";
                            System.err.println("Printing a file: " + newHtmlFile);
                            File newHTML = new File(newHtmlFile);
                            int t = 0;
                            while (newHTML.exists()) {
                                newHTML = new File(folder.getAbsolutePath() + "/" + f.getName() + "_"
                                        + rankedResult.clueWebID + "_" + sentLength + "." + t + ".html");
                                t++;
                            }
                            mustache.execute(new PrintWriter(new FileWriter(newHTML)),
                                    new generators(query, relevantInformationExamples,
                                            irrelevantInformationExamples, sentences.subList(startID, endID),
                                            queryId, rank))
                                    .flush();
                            startID = endID;
                        }
                    }
                }
            }

        }
    }
    System.out.println("Printed " + countClueWeb + " documents with " + countSentence + " sentences");
}

From source file:com.joliciel.csvLearner.utils.LogUtils.java

/**
Return the current exception & stack trace as a String.
*//*from w  ww.  j  av  a  2s .c o m*/
public static String getErrorString(Throwable e) {
    String s = null;
    try {
        StringWriter sw = new StringWriter();
        PrintWriter ps = new PrintWriter((Writer) sw);
        e.printStackTrace(ps);
        sw.flush();
        s = sw.toString();
        sw.close();
    } catch (IOException ioe) {
        // do nothing!
    }
    return s;
}

From source file:Main.java

/** 
 * Write the <code>Document</code> in memory out to a standard XML file.
 * @param  doc  the <code>Document</code> object for the XML file to list
 * @param  strFilePath  the XML file to write to
 * @throws custom custom exception if file is not writeable
 * @throws ioe IOException if an error occurs on file creation
 * @throws fnfe FileNotFoundException if PrintWriter constructor fails
 *///from w w w  .j  av  a2s  .  c  o  m
public static void WriteXMLFile2(Document doc, String strFilePath) throws Exception {
    // open file for writing
    File file = new File(strFilePath);

    // ensure that file is writeable
    try {
        file.createNewFile();
        if (!file.canWrite()) {
            throw new Exception("FileNotWriteable");
        }
    } catch (IOException ioe) {
        throw ioe;
    }

    // create a PrintWriter to write the XML file to
    PrintWriter pw = null;
    try {
        pw = new PrintWriter(file);
    } catch (FileNotFoundException fnfe) {
        throw fnfe;
    }

    // write out the serialized form
    pw.print(getXMLListing(doc));
    pw.close();
}

From source file:mx.unam.ecologia.gye.coalescence.app.CreateSampleConfiguration.java

protected static final void writeSampleConfig(List leaves, String fname) {
    try {//from w w  w. j a  v  a2  s .c  o m

        FileOutputStream fout = new FileOutputStream(fname);
        PrintWriter pw = new PrintWriter(fout);
        HaplotypeFreqSet len1 = new HaplotypeFreqSet(new CompoundSequenceLengthComparator());
        HaplotypeFreqSet len2 = new HaplotypeFreqSet(new CompoundSequenceLengthComparator());
        HaplotypeFreqSet ident = new HaplotypeFreqSet(new CompoundSequenceIdentityComparator());

        for (int i = 0; i < leaves.size(); i++) {
            UniParentalGene upgene = (UniParentalGene) leaves.get(i);
            CompoundSequence h = upgene.getCompoundSequence();
            len1.add(h);
            ident.add(h);
            CompoundSequence cs = h.getCopy();
            cs.setLocus(true);
            len2.add(cs);

            int numloc = h.getSequenceCount();
            for (int n = 0; n < numloc; n++) {
                Sequence s = h.get(n);
                pw.print(s.toFullString());
                pw.print(" ");
            }
            pw.println();
        }
        //print length as locus
        pw.println();
        pw.println("Haplotypes by Length (locus)");
        pw.println(len2.toString());
        pw.println("Haplotypes by Length (multilocus)");
        pw.println(len1.toString());
        pw.println("Haplotypes by Identity");
        pw.println(ident.toFullString());
        pw.println();

        //System.out.println("TEST");
        //ident.sort(new CSAncestryComparator());
        //System.out.println(ident.toFullString());
        //System.out.println(ident.findMostFrequent() + 1);

        pw.flush();
        pw.close();
        fout.close();
    } catch (IOException ex) {
        CreateSampleConfiguration.log.error("writeSampleConfig()", ex);
    }

}

From source file:Main.java

public static String toStringE(Node element) {
    try {//from  w  w w .  j a  va 2 s .c  o m
        if (element == null) {
            return "null";
        }
        Source source = new DOMSource(element);

        StringWriter stringWriter = new StringWriter();
        try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
            Result result = new StreamResult(printWriter);

            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.transform(source, result);
        }
        return stringWriter.toString();
    } catch (IllegalArgumentException | TransformerException ex) {
        throw new Error(ex);
    }
}

From source file:Main.java

/** Pops up a message box, blocking the current thread. */
public static void pause(final Throwable t) {
    final CharArrayWriter caw = new CharArrayWriter();
    t.printStackTrace(new PrintWriter(caw));
    pause(caw.toString());/*www  . ja v  a  2s  . c o m*/
}