Example usage for org.apache.commons.io FileUtils writeStringToFile

List of usage examples for org.apache.commons.io FileUtils writeStringToFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils writeStringToFile.

Prototype

public static void writeStringToFile(File file, String data) throws IOException 

Source Link

Document

Writes a String to a file creating the file if it does not exist using the default encoding for the VM.

Usage

From source file:net.itransformers.idiscover.v2.core.listeners.network.NetworkGraphmlFileLogDiscoveryListener.java

@Override
public void networkDiscovered(NetworkDiscoveryResult result) {
    File baseDir = new File(projectPath);
    if (!baseDir.exists())
        baseDir.mkdir();/*from w ww .j a v  a 2  s .c  o m*/

    File labelDirPath = new File(baseDir, labelDirName);
    if (!labelDirPath.exists())
        labelDirPath.mkdir();

    File graphmlDir = new File(labelDirPath, graphmlDirName);
    if (!graphmlDir.exists())
        graphmlDir.mkdir();

    Map<String, NodeDiscoveryResult> discoveryResultMap = result.getDiscoveredData();
    for (String node : discoveryResultMap.keySet()) {

        byte[] discoveredDeviceData = (byte[]) discoveryResultMap.get(node).getDiscoveredData("graphml");

        try {
            final String fileName = ProjectConstants.networkGraphmlFileName;
            final File nodeFile = new File(graphmlDir, fileName);
            String graphml = new String(discoveredDeviceData);
            FileUtils.writeStringToFile(nodeFile, graphml);
            FileWriter writer = new FileWriter(new File(labelDirPath, "undirected" + ".graphmls"), true);
            writer.append(String.valueOf(fileName)).append("\n");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

From source file:com.adguard.compiler.SettingUtils.java

public static void writeLocalScriptRulesToFile(File dest, boolean useLocalScriptRules,
        Map<Integer, List<String>> filtersScriptRules) throws IOException {
    String scriptRules = getScriptRulesText(filtersScriptRules);
    String settings = String.format(LOCAL_SCRIPT_RULES_FILE_TEMPLATE, useLocalScriptRules, scriptRules);
    FileUtils.writeStringToFile(getLocalScriptRulesFile(dest), settings);
}

From source file:com.github.neio.filesystem.paths.TestFilePath.java

@Test
public void testSize() throws IOException {
    FileUtils.writeStringToFile(new File(testDir, "testFile"), "Hello World");

    Assert.assertEquals(11, new FilePath("./testTempDir/testFile").size());
}

From source file:com.screenslicer.core.scrape.ProcessPage.java

public static List<Result> perform(RemoteWebDriver driver, int page, String query, String[] whitelist,
        String[] patterns, UrlTransform[] transforms) throws ActionFailed {
    try {/* ww w. j  a v  a 2  s. co m*/
        Element element = Util.openElement(driver, whitelist, patterns, transforms);
        trim(element);
        if (WebApp.DEBUG) {
            try {
                FileUtils.writeStringToFile(new File("./" + System.currentTimeMillis()), element.outerHtml());
            } catch (IOException e) {
            }
        }
        Map<String, Object> cache = new HashMap<String, Object>();
        List<Result> results = perform(element, page, query, driver.getCurrentUrl(), true, cache);
        if (results == null || results.isEmpty()) {
            results = perform(element, page, query, driver.getCurrentUrl(), false, cache);
        }
        return results;
    } catch (Throwable t) {
        Log.exception(t);
        throw new ActionFailed(t);
    }
}

From source file:it.drwolf.ridire.utility.RIDIREPlainTextCleaner.java

public void cleanTextFile(File f) throws IOException {
    File tmpFile = new File(f.getCanonicalPath() + ".tmp");
    FileUtils.writeStringToFile(tmpFile, this.getCleanText(f));
    FileUtils.deleteQuietly(f);/*from w  w  w  . j  a  va  2  s.  c  om*/
    FileUtils.moveFile(tmpFile, f);
}

From source file:jobs.ComputeIndexDistribution.java

@Override
public void doJob() throws Exception {

    Logger.info("Job started...");

    Directory directory = FSDirectory.open(VirtualFile.fromRelativePath("/indexes/index-2013").getRealFile());
    DirectoryReader ireader = DirectoryReader.open(directory);

    //Returns an error is the field does not exists
    //Do the same for abstract (first if possible)
    Terms terms = SlowCompositeReaderWrapper.wrap(ireader).terms("contents");
    TermsEnum iterator = terms.iterator(null);
    BytesRef byteRef;// w w w  . j  av a  2  s. c  o  m

    Map<Integer, Integer> distribution = new HashMap<Integer, Integer>();

    while ((byteRef = iterator.next()) != null) {
        String term = new String(byteRef.bytes, byteRef.offset, byteRef.length);

        if (!term.contains("_")) {

            int frequency = iterator.docFreq();

            if (distribution.get(frequency) != null) {
                Integer oldValue = distribution.get(frequency);
                Integer newValue = oldValue + 1;
                distribution.put(frequency, newValue);
            } else {
                distribution.put(frequency, 1);
            }

            Logger.info("Term: " + term + " - freq: " + frequency);
        }
    }

    File file = new File("data/distribution-frequency-in-corpus-2013-shingles.csv");
    StringBuilder sb = new StringBuilder();
    for (Integer frequency : distribution.keySet()) {
        sb.append(frequency).append("\t").append(distribution.get(frequency)).append("\n");
    }
    FileUtils.writeStringToFile(file, sb.toString());
    Logger.info("Job finished.");
}

From source file:it.geosolutions.geobatch.actions.geonetwork.GeonetworkActionDeleteTest.java

protected void insertSome() throws IOException, GNException {
    final String TITLETOKEN = "TOKEN_FOR_TITLE";

    GNClient client = createClientAndLogin();

    File origFile = loadFile("metadata_token.xml");
    String orig = FileUtils.readFileToString(origFile);

    File tempFile = File.createTempFile("gbtest", ".xml");
    FileUtils.forceDeleteOnExit(tempFile);

    for (int i = 0; i < 5; i++) {
        String title = "GeoBatch GeoNetworkAction test" + i + " ACK00";
        String test = orig.replace(TITLETOKEN, title);
        FileUtils.writeStringToFile(tempFile, test);
        long id = insertMetadata(client, tempFile);
        LOGGER.info("Created test metadata id:" + id + " [" + title + "]");
    }//from w w  w  . j  a  v  a 2 s. c  o  m

    for (int i = 0; i < 7; i++) {
        String title = "GeoBatch GeoNetworkAction test" + i + " ACK99";
        String test = orig.replace(TITLETOKEN, title);
        FileUtils.writeStringToFile(tempFile, test);
        long id = insertMetadata(client, tempFile);
        LOGGER.info("Created test metadata id:" + id + " [" + title + "]");
    }
}

From source file:com.thoughtworks.go.config.GoConfigMigration.java

public File revertFileToVersion(File configFile, GoConfigRevision currentConfigRevision) {
    File backupFile = getBackupFile(configFile, "invalid.");
    try {//from   ww w  . j  a v a 2 s .  c o  m
        backup(configFile, backupFile);
        FileUtils.writeStringToFile(configFile, currentConfigRevision.getContent());
    } catch (IOException e1) {
        throw new RuntimeException(
                String.format("Could not write to config file '%s'.", configFile.getAbsolutePath()), e1);
    }

    return backupFile;
}

From source file:com.baasbox.db.async.ExportJob.java

@Override
public void run() {
    FileOutputStream dest = null;
    ZipOutputStream zip = null;/*ww w. j a  v  a  2  s.c om*/
    FileOutputStream tempJsonOS = null;
    FileInputStream in = null;
    try {
        //File f = new File(this.fileName);
        File f = File.createTempFile("export", ".temp");

        dest = new FileOutputStream(f);
        zip = new ZipOutputStream(dest);

        File tmpJson = File.createTempFile("export", ".json");
        tempJsonOS = new FileOutputStream(tmpJson);
        DbHelper.exportData(this.appcode, tempJsonOS);
        BaasBoxLogger.info(String.format("Writing %d bytes ", tmpJson.length()));
        tempJsonOS.close();

        ZipEntry entry = new ZipEntry("export.json");
        zip.putNextEntry(entry);
        in = new FileInputStream(tmpJson);
        final int BUFFER = BBConfiguration.getImportExportBufferSize();
        byte buffer[] = new byte[BUFFER];

        int length;
        while ((length = in.read(buffer)) > 0) {
            zip.write(buffer, 0, length);
        }
        zip.closeEntry();
        in.close();

        File manifest = File.createTempFile("manifest", ".txt");
        FileUtils.writeStringToFile(manifest,
                BBInternalConstants.IMPORT_MANIFEST_VERSION_PREFIX + BBConfiguration.getApiVersion());

        ZipEntry entryManifest = new ZipEntry("manifest.txt");
        zip.putNextEntry(entryManifest);
        zip.write(FileUtils.readFileToByteArray(manifest));
        zip.closeEntry();

        tmpJson.delete();
        manifest.delete();

        File finaldestination = new File(this.fileName);
        FileUtils.moveFile(f, finaldestination);

    } catch (Exception e) {
        BaasBoxLogger.error(ExceptionUtils.getMessage(e));
    } finally {
        try {
            if (zip != null)
                zip.close();
            if (dest != null)
                dest.close();
            if (tempJsonOS != null)
                tempJsonOS.close();
            if (in != null)
                in.close();

        } catch (Exception ioe) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(ioe));
        }
    }
}

From source file:cc.kave.episodes.mining.reader.FileReaderTest.java

@Test
public void oneNodeEpisodes() throws IOException {
    StringBuilder sb = new StringBuilder();
    sb.append("1,0.001\n");
    sb.append("2,0.002\n");
    sb.append("3,0.003\n");
    sb.append("4,0.004\n");
    sb.append("5,0.005\n");
    sb.append("6,0.006\n");
    sb.append("7,0.007\n");
    sb.append("8,0.008\n");
    sb.append("9,0.009\n");
    sb.append("10,0.01\n");

    String content = sb.toString();

    File file = getFilePath();/*from  www.j a v  a 2 s .  co m*/

    try {
        FileUtils.writeStringToFile(file, content);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    List<String> expected = new LinkedList<String>();
    expected.add("1,0.001");
    expected.add("2,0.002");
    expected.add("3,0.003");
    expected.add("4,0.004");
    expected.add("5,0.005");
    expected.add("6,0.006");
    expected.add("7,0.007");
    expected.add("8,0.008");
    expected.add("9,0.009");
    expected.add("10,0.01");

    List<String> actuals = sut.readFile(file);

    assertEquals(expected, actuals);
}