Example usage for java.io FileWriter write

List of usage examples for java.io FileWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:com.sri.ai.praise.demo.ChurchPanel.java

private void saveToFile() throws IOException {
    if (!currentChurchFile.exists()) {
        currentChurchFile.createNewFile();
    }// w  w w.  jav  a2  s . c o  m

    FileWriter fileWriter = new FileWriter(currentChurchFile);
    fileWriter.write(churchEditor.getText());
    fileWriter.close();

    churchEditor.discardAllEdits();
}

From source file:com.linkedin.helix.tools.ZKDumper.java

public void download(String zkPath, String fsPath) throws Exception {

    List<String> children = client.getChildren(zkPath);
    if (children != null && children.size() > 0) {
        new File(fsPath).mkdirs();
        for (String child : children) {
            String childPath = zkPath.equals("/") ? "/" + child : zkPath + "/" + child;
            download(childPath, fsPath + "/" + child);
        }//from www  .j  a va  2  s.  co  m
    } else {
        System.out.println("Saving " + zkPath + " to " + new File(fsPath + suffix).getCanonicalPath());
        FileWriter fileWriter = new FileWriter(fsPath + suffix);
        Object readData = client.readData(zkPath);
        if (readData != null) {
            fileWriter.write((String) readData);
        }
        fileWriter.close();
    }
}

From source file:com.newrelic.agent.Obfuscation.Proguard.java

public void findAndSendMapFile() {
    /*  45 */ String mappingString = "";
    /*     *//*w ww  . jav  a 2 s.  c o m*/
    /*  47 */ if (getProjectRoot() != null) {
        /*  48 */ if (!fetchConfiguration()) {
            /*  49 */ return;
            /*     */ }
        /*     */
        /*  52 */ File projectRoot = new File(getProjectRoot());
        /*  53 */ IOFileFilter fileFilter = FileFilterUtils.nameFileFilter("mapping.txt");
        /*  54 */ Collection files = FileUtils.listFiles(projectRoot, fileFilter, TrueFileFilter.INSTANCE);
        /*     */
        /*  56 */ if (files.isEmpty()) {
            /*  57 */ this.log.error(
                    "While evidence of ProGuard was detected, New Relic failed to find your mapping.txt file.");
            /*  58 */ this.log
                    .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually.");
            /*     */ }
        /*     */
        /*  61 */ for (File file : files) {
            /*  62 */ this.log.info("Found mapping.txt: " + file.getPath());
            /*     */ try
            /*     */ {
                /*  66 */ FileWriter fileWriter = new FileWriter(file, true);
                /*  67 */ fileWriter.write("# NR_BUILD_ID: " + NewRelicClassVisitor.getBuildId());
                /*  68 */ fileWriter.close();
                /*     */
                /*  70 */ mappingString = mappingString + FileUtils.readFileToString(file);
                /*     */ } catch (FileNotFoundException e) {
                /*  72 */ this.log.error("Unable to open your mapping.txt file: " + e.getLocalizedMessage());
                /*  73 */ this.log
                        .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually.");
                /*     */ } catch (IOException e) {
                /*  75 */ this.log.error("Unable to open your mapping.txt file: " + e.getLocalizedMessage());
                /*  76 */ this.log
                        .error("To de-obfuscate your builds, you'll need to upload your mapping.txt manually.");
                /*     */ }
            /*     */ }
        /*     */
        /*  80 */ if (this.uploadingEnabled)
            /*  81 */ sendMapping(mappingString);
        /*     */ }
    /*     */ }

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.ManifestParserImplFastTest.java

@Test
public void testUpdateFileToManifest() throws IOException, NoSuchAlgorithmException, ParseException {
    // write a new manifest file (to make sure we know what is in it)
    final File manifest = new File(
            SAMPLE_DIR + "qclive/manifestParser/center_disease.platform.Level_1.1.0.0/TEMP_MANIFEST.txt");
    FileWriter writer = null;
    try {/*from  w w  w  . j  av a2  s .c o  m*/
        //noinspection IOResourceOpenedButNotSafelyClosed
        writer = new FileWriter(manifest);
        writer.write("12345  file1\n");
    } finally {
        IOUtils.closeQuietly(writer);
    }

    List<File> filesToBeAdded = new ArrayList<File>();
    // this file should be added to the manifest
    File toAdd = createNewFile("file2");
    filesToBeAdded.add(toAdd);
    toAdd = createNewFile("file3");
    filesToBeAdded.add(toAdd);

    List<File> filesToBeRemoved = Arrays.asList(new File[] { new File("file1") });

    try {
        parser.updateManifest(filesToBeAdded, filesToBeRemoved, manifest);
        final Map<String, String> manifestContent = parser.parseManifest(manifest);
        // only care that file has been added, not what the MD5 is
        assertTrue("Error updating manifest file", manifestContent.containsKey("file2"));
        assertTrue("Error updating manifest file", manifestContent.containsKey("file3"));
        assertFalse("Error updating manifest file", manifestContent.containsKey("file1"));
    } finally {
        manifest.deleteOnExit();
        for (File file : filesToBeAdded) {
            if (file.exists()) {
                file.delete();
            }
        }
    }
}

From source file:com.amazonaws.services.iot.demo.danbo.rpi.Servo.java

public void run() {
    try {/*from  ww  w.  j av a  2  s.c  o  m*/
        log.debug("starting execution of thread: " + threadName);
        // calls the servoblaster command to move the servo according to the
        // selected angle
        try {
            String servoBlasterDevice = "/dev/servoblaster";
            File servoBlasterDev = new File(servoBlasterDevice);
            if (!servoBlasterDev.exists()) {
                throw new FileNotFoundException("Servoblaster not found at " + servoBlasterDevice
                        + ". Please check https://github.com/richardghirst/PiBits/tree/master/ServoBlaster for details.");
            }
            FileWriter writer = new FileWriter(servoBlasterDev);
            StringBuilder b = new StringBuilder();
            b.append("0").append('=').append(Integer.toString(angle + 150)).append('\n');
            try {
                writer.write(b.toString());
                writer.flush();
            } catch (IOException e) {
                try {
                    writer.close();
                } catch (IOException ignore) {
                }
            }
            try {
                writer.write(b.toString());
                writer.flush();
            } catch (IOException e) {
                throw new RuntimeException("Failed to write to /dev/servoblaster device", e);
            }
        } catch (Exception e) {
            System.err.println(String.format("Could not execute the servoblaster command"));
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        log.debug("finishing execution of thread: " + threadName);
    }
}

From source file:i.am.jiongxuan.deapk.Deapk.java

private void writeError(String errorTitle, List<String> errors) {
    try {/* www  . jav  a  2s .  c  o m*/
        FileWriter errorWriter = new FileWriter(mErrorFile);
        errorWriter.write(errorTitle + "\r\n");

        for (String error : errors) {
            errorWriter.write("      " + error + "\r\n");
        }

        if (errorWriter != null) {
            errorWriter.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.epam.controllers.pages.graphviz.GraphViz.java

/**
 * Writes the source of the graph in a file, and returns the written file
 * as a File object.//from w  w  w.j  a v a  2 s .  c o  m
 * @param str Source of the graph (in dot language).
 * @return The file (as a File object) that contains the source of the graph.
 */
private File writeDotSourceToFile(String str) throws java.io.IOException {
    File temp;
    try {
        temp = File.createTempFile("graph_", ".dot.tmp", new File(GraphViz.TEMP_DIR));
        FileWriter fout = new FileWriter(temp);
        fout.write(str);
        fout.close();
    } catch (Exception e) {
        log.error("Error: I/O error while writing the dot source to temp file!", e);
        return null;
    }
    return temp;
}

From source file:bigtweet.BTSimBatch.java

/**
 * Update the output json object and copy it to the output file
 *
 * @param distances/*from  w w w  .ja  v  a  2 s .  c om*/
 * @param get
 */
private void updateOutputJsonFile(int parametersValuesIndex) {
    //calculate elements for update    
    JSONObject parameters = (JSONObject) parametersValues.get(parametersValuesIndex);

    //update attributes and json ouput object
    this.experimentConducted = parametersValuesIndex + 1;
    JSONObject experimentObject = new JSONObject();
    experimentObject.put("experimentID", parametersValuesIndex);
    experimentObject.put("parameters", parameters);

    //read for each experiment results the best values and values for this experiment
    JSONObject results = new JSONObject();
    JSONObject bestResults = new JSONObject();
    for (BatchExperimentsResults r : resultsForDatasets) {
        r.updateMetricsForParametersValues(parametersValues, parametersValuesIndex); //update metrics for one expermioments and for all
        results.put(r.getName(), r.getMetricsForLastExperiment());
        bestResults.put(r.getName(), r.getMetricsForAllExperiments());
    }
    experimentObject.put("results", results);
    experiments.add(experimentObject);
    output.put("experiments", experiments);
    output.put("bestResults", bestResults);

    //write json file
    FileWriter file;
    try {
        file = new FileWriter(batchOutputFile);
        file.write(output.toJSONString());
        file.flush();
        file.close();
    } catch (Exception ex) {
        Logger.getLogger(BTSimBatch.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.yahoo.labs.samoa.streams.fs.LocalFileStreamSourceTest.java

private void writeSimpleFiles(String path, String ext, int numOfFiles) {
    // Create folder
    File folder = new File(path);
    if (!folder.exists()) {
        try {//w  w w . j  a va  2s . com
            folder.mkdir();
        } catch (SecurityException se) {
            fail("Failed creating directory:" + path + se);
        }
    }

    // Write files
    for (int i = 1; i <= numOfFiles; i++) {
        String fn = null;
        if (ext != null) {
            fn = Integer.toString(i) + "." + ext;
        } else {
            fn = Integer.toString(i);
        }

        try {
            FileWriter fwr = new FileWriter(new File(path, fn));
            fwr.write(Integer.toString(i));
            fwr.close();
        } catch (IOException ioe) {
            fail("Fail writing to input file: " + fn + " in directory: " + path + ioe.getMessage());
        }
    }
}

From source file:io.hops.experiments.stats.TransactionStatsCumulative.java

private void generateGraphsFor(String transaction, File baseDir, String[] columns, String graphCol,
        String xlabel, String ylabel, String title) throws IOException {
    String[] datFiles = baseDir.list();
    int i = 0;/*from w  w  w.  j  a v a2  s  . c o  m*/
    for (String col : columns) {
        if (col.equals(graphCol)) {
            break;
        }
        i++;
    }

    Arrays.sort(datFiles, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
        }
    });

    int baseOffset = 1;
    int[] lines = new int[RESOLVING_CACHES.length];
    String[] linesTitles = new String[RESOLVING_CACHES.length];

    for (int c = 0; c < RESOLVING_CACHES.length; c++) {
        lines[c] = baseOffset + i * 3 + 2;
        linesTitles[c] = getResolvingCacheTitle(RESOLVING_CACHES[c]);
        baseOffset += (columns.length
                + (isResolvingCache(RESOLVING_CACHES[c]) ? RESOLVING_CACHE_COLUMNS.length : 0)) * 3;
    }

    for (String datFile : datFiles) {
        String name = transaction.replace("_", "-") + "-" + datFile + "-" + title;
        String graph = getGnuScript(name, name, xlabel, ylabel, datFile, lines, linesTitles);
        FileWriter writer = new FileWriter(new File(baseDir, name + ".gnu"));
        writer.write(graph);
        writer.close();
    }

    for (int rccol = 0; rccol < RESOLVING_CACHE_COLUMNS.length; rccol++) {

        baseOffset = 1 + columns.length * 3;

        for (int rc = 1; rc < RESOLVING_CACHES.length; rc++) {
            String name = transaction.replace("_", "-") + "-" + RESOLVING_CACHE_COLUMNS[rccol] + "-"
                    + getResolvingCacheTitle(RESOLVING_CACHES[rc]);

            int line = baseOffset + (columns.length + rccol) * 3 + 2;

            String graph = getGnuScript(name, name, xlabel, rccol == 1 ? "RoundTrips" : ylabel, datFiles, line);

            FileWriter writer = new FileWriter(new File(baseDir, name + ".gnu"));
            writer.write(graph);
            writer.close();

            baseOffset += (columns.length + RESOLVING_CACHE_COLUMNS.length) * 3;
        }
    }
}