Example usage for java.io FileWriter FileWriter

List of usage examples for java.io FileWriter FileWriter

Introduction

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

Prototype

public FileWriter(FileDescriptor fd) 

Source Link

Document

Constructs a FileWriter given a file descriptor, using the platform's java.nio.charset.Charset#defaultCharset() default charset .

Usage

From source file:Main.java

/**
 * Write the String into the given File//from   w  ww  .ja  v a 2  s  . c  om
 * @param baseString
 * @param mainStyleFile
 */
public static void writeStyleFile(String baseString, File mainStyleFile) {
    FileWriter fw = null;
    try {
        fw = new FileWriter(mainStyleFile);
        fw.write(baseString);
        Log.i("STYLE", "Style File updated:" + mainStyleFile.getPath());
    } catch (FileNotFoundException e) {
        Log.e("STYLE", "unable to write open file:" + mainStyleFile.getPath());
    } catch (IOException e) {
        Log.e("STYLE", "error writing the file: " + mainStyleFile.getPath());
    } finally {
        try {
            if (fw != null) {
                fw.close();
            }
        } catch (IOException e) {
            // ignored
        }
    }
}

From source file:com.reversemind.glia.test.go3.java

public static void save(String fileName, String string) throws Exception {

    BufferedWriter bw = new BufferedWriter(new FileWriter(new File(fileName)));
    bw.write(string + "\n");
    bw.flush();//from   ww  w .ja v  a  2s . c o  m
    bw.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);//from   w ww . j  av a 2  s  .co  m
    out.println();
    fw.close();
    out.close();
}

From source file:Main.java

/**
 * Print out the spike trains so it can be analyzed by plotting software
 * @param file//  w  ww  .  j  av  a  2  s  .  c  o m
 * @param array
 */
public static void print(File file, double[] array) {
    FileWriter fstream = null;
    BufferedWriter out = null;

    try {
        fstream = new FileWriter(file);
        out = new BufferedWriter(fstream);
        for (int i = 0; i < array.length; i++) {
            out.write(array[i] + "\t");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fstream != null) {
            try {
                fstream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

From source file:Main.java

/**
 * Print out the spike trains so it can be analyzed by plotting software
 * @param file//from   w  w  w .j av  a2s. c om
 * @param array
 */
public static void printArray(File file, double[] x, double[] y) {
    FileWriter fstream = null;
    BufferedWriter out = null;

    try {
        fstream = new FileWriter(file);
        out = new BufferedWriter(fstream);
        for (int i = 0; i < x.length; i++) {
            out.write(x[i] + "\t");
        }
        out.write("\r\n");
        for (int i = 0; i < y.length; i++) {
            out.write(y[i] + "\t");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fstream != null) {
            try {
                fstream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

From source file:Main.java

public static void write(String text, File dst) throws IOException {
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(dst));
    bufferedWriter.write(text);//  w w  w.  j a  va 2  s  . c  o  m
    bufferedWriter.flush();
    bufferedWriter.close();
}

From source file:Main.java

public static void saveDocument(Document document, String path)
        throws TransformerConfigurationException, TransformerFactoryConfigurationError,
        TransformerFactoryConfigurationError, TransformerException, IOException {

    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    DOMSource dom = new DOMSource(document);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute("indent-number", 4);

    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(dom, sr);//from ww  w .  ja v  a  2 s.c o m

    String string = sw.toString();
    FileWriter fw = new FileWriter(new File(path));
    fw.write(string);
    fw.close();
}

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 ww .jav  a 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: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:bizlogic.Sensors.java

public static void list(Connection DBcon) throws IOException, ParseException, SQLException {

    Statement st = null;//from  w w w  .j  av a  2 s  .c om
    ResultSet rs = null;

    try {
        st = DBcon.createStatement();
        rs = st.executeQuery("SELECT * FROM USERCONF.SENSORLIST");

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Sensors.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);
    }
    try {
        FileWriter sensorsFile = new FileWriter("/var/lib/tomcat8/webapps/ROOT/Records/sensors.json");
        sensorsFile.write("");
        sensorsFile.flush();

        JSONParser parser = new JSONParser();

        JSONObject Records = new JSONObject();

        JSONObject operation_Obj = new JSONObject();
        JSONObject operand_Obj = new JSONObject();
        JSONObject unit_Obj = new JSONObject();
        JSONObject name_Obj = new JSONObject();
        JSONObject ip_Obj = new JSONObject();
        JSONObject port_Obj = new JSONObject();

        int _total = 0;

        JSONArray sensorList = new JSONArray();

        while (rs.next()) {

            JSONObject sensor_Obj = new JSONObject();
            int id = rs.getInt("sensor_id");
            String operation = rs.getString("operation");
            int operand = rs.getInt("operand");
            String unit = rs.getString("unit");
            String name = rs.getString("name");
            String ip = rs.getString("IP");
            int port = rs.getInt("port");

            sensor_Obj.put("recid", id);
            sensor_Obj.put("operation", operation);
            sensor_Obj.put("operand", operand);
            sensor_Obj.put("unit", unit);
            sensor_Obj.put("name", name);
            sensor_Obj.put("IP", ip);
            sensor_Obj.put("port", port);

            sensorList.add(sensor_Obj);
            _total++;

        }
        rs.close();

        Records.put("total", _total);
        Records.put("records", sensorList);

        sensorsFile.write(Records.toJSONString());
        sensorsFile.flush();
        sensorsFile.close();
    }

    catch (IOException ex) {
        Logger.getLogger(Sensors.class.getName()).log(Level.WARNING, null, ex);
    }
}