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:com.datatorrent.lib.io.fs.DirectoryScanInputOperatorTest.java

@SuppressWarnings({ "rawtypes", "unchecked" })
@Test/*w w  w  .j  av  a 2  s .  c om*/
public void testDirectoryScan() throws InterruptedException, IOException {

    //Create the directory and the files used in the test case
    File baseDir = new File(dirName);

    // if the directory does not exist, create it
    if (!baseDir.exists()) {
        System.out.println("creating directory: " + dirName);
        boolean result = baseDir.mkdir();

        if (result) {
            System.out.println("base directory created");

            //create sub-directory

            File subDir = new File(dirName + "/subDir");

            // if the directory does not exist, create it
            if (!subDir.exists()) {
                System.out.println("creating subdirectory: " + dirName + "/subDir");
                boolean subDirResult = subDir.mkdir();

                if (subDirResult) {
                    System.out.println("sub directory created");
                }
            }
        } else {
            System.out.println("Failed to create base directory");
            return;
        }
    }

    //Create the files inside base dir     
    int numOfFilesInBaseDir = 4;
    for (int num = 0; num < numOfFilesInBaseDir; num++) {
        String fileName = dirName + "/testFile" + String.valueOf(num + 1) + ".txt";
        File file = new File(fileName);

        if (file.createNewFile()) {
            System.out.println(fileName + " is created!");
            FileUtils.writeStringToFile(file, fileName);

        } else {
            System.out.println(fileName + " already exists.");
        }
    }

    //Create the files inside base subDir  
    int numOfFilesInSubDir = 6;
    for (int num = 0; num < numOfFilesInSubDir; num++) {
        String fileName = dirName + "/subDir/testFile" + String.valueOf(num + numOfFilesInBaseDir + 1) + ".txt";
        File file = new File(fileName);

        if (file.createNewFile()) {
            System.out.println(fileName + " is created!");
            FileUtils.writeStringToFile(file, fileName);
        } else {
            System.out.println(fileName + " already exists.");
        }
    }

    DirectoryScanInputOperator oper = new DirectoryScanInputOperator();
    oper.setDirectoryPath(dirName);
    oper.setScanIntervalInMilliSeconds(1000);
    oper.activate(null);

    CollectorTestSink sink = new CollectorTestSink();
    oper.outport.setSink(sink);

    //Test if the existing files in the directory are emitted.
    Thread.sleep(1000);
    oper.emitTuples();

    Assert.assertTrue("tuple emmitted: " + sink.collectedTuples.size(), sink.collectedTuples.size() > 0);
    Assert.assertEquals(sink.collectedTuples.size(), 10);

    //Test if the new file added is detected
    sink.collectedTuples.clear();

    File oldFile = new File("../library/src/test/resources/directoryScanTestDirectory/testFile1.txt");
    File newFile = new File("../library/src/test/resources/directoryScanTestDirectory/newFile.txt");
    FileUtils.copyFile(oldFile, newFile);

    int timeoutMillis = 2000;
    while (sink.collectedTuples.isEmpty() && timeoutMillis > 0) {
        oper.emitTuples();
        timeoutMillis -= 20;
        Thread.sleep(20);
    }

    Assert.assertTrue("tuple emmitted: " + sink.collectedTuples.size(), sink.collectedTuples.size() > 0);
    Assert.assertEquals(sink.collectedTuples.size(), 1);

    //clean up the directory to initial state
    newFile.delete();

    oper.deactivate();
    oper.teardown();

    //clean up the directory used for the test      
    FileUtils.deleteDirectory(baseDir);
}

From source file:cc.recommenders.io.Directory.java

public void writeContent(String content, String relativePath) throws IOException {
    File file = new File(rootDir, relativePath);
    FileUtils.writeStringToFile(file, content);
}

From source file:eu.udig.omsbox.view.actions.OmsScriptGenerationAction.java

public void run(IAction action) {
    if (view instanceof OmsBoxView) {
        OmsBoxView omsView = (OmsBoxView) view;
        try {//from   ww w .  j ava2 s. c o m
            String script = omsView.generateScriptForSelectedModule();
            if (script == null) {
                return;
            }
            Program program = Program.findProgram(".txt");
            if (program != null) {
                File tempFile = File.createTempFile("omsbox_", ".oms");
                if (tempFile == null || !tempFile.exists() || tempFile.getAbsolutePath() == null) {
                    // try with user's home folder
                    String ts = new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS);
                    String userHomePath = System.getProperty("user.home"); //$NON-NLS-1$

                    File userHomeFile = new File(userHomePath);
                    if (!userHomeFile.exists()) {
                        String message = "Unable to create the oms script both in the temp folder and user home. Check your permissions.";
                        ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, OmsBoxPlugin.PLUGIN_ID,
                                new RuntimeException());
                        return;
                    }
                    tempFile = new File(userHomeFile, "omsbox_" + ts + ".oms");
                }
                FileUtils.writeStringToFile(tempFile, script);

                program.execute(tempFile.getAbsolutePath());

                // cleanup when leaving uDig
                // tempFile.deleteOnExit();
            } else {
                // make it the good old way prompting
                FileDialog fileDialog = new FileDialog(view.getSite().getShell(), SWT.SAVE);
                String path = fileDialog.open();
                if (path == null || path.length() < 1) {
                    return;
                }
                FileUtils.writeStringToFile(new File(path), script);
            }

        } catch (Exception e) {
            e.printStackTrace();
            String message = "An error ocurred while generating the script.";
            ExceptionDetailsDialog.openError(null, message, IStatus.ERROR, OmsBoxPlugin.PLUGIN_ID, e);
        }

    }
}

From source file:jenkins.plugins.shiningpanda.scm.CoverageSCM.java

public boolean checkout(AbstractBuild<?, ?> build, Launcher launcher, FilePath remoteDir,
        BuildListener listener, File changeLogFile) throws IOException, InterruptedException {
    for (String htmlDir : htmlDirs) {
        File htmlDirFile = new File(build.getWorkspace().getRemote(), htmlDir);
        htmlDirFile.mkdirs();/*  w  ww .  j ava 2s  . c om*/
        FileUtils.writeStringToFile(new File(htmlDirFile, "coverage_html.js"), "");
        FileUtils.writeStringToFile(new File(htmlDirFile, "status.dat"), "");
        FileUtils.writeStringToFile(new File(htmlDirFile, "index.html"), "");
    }
    return createEmptyChangeLog(changeLogFile, listener, "log");
}

From source file:net.cpollet.jixture.fixtures.TestFileFixture.java

@Test
public void getInputStreamReturnsInputStreamFromPath() throws IOException {
    // GIVEN/*from   ww w .  j  a v a 2 s.c  o m*/
    File file = folder.newFile("foo.txt");
    FileUtils.writeStringToFile(file, "someContent");

    String filePath = file.getAbsoluteFile().getAbsolutePath();
    FileFixture fileFixture = buildFixture(filePath);

    // WHEN
    InputStream actualInputStream = fileFixture.getInputStream();

    // THEN
    InputStream expectedInputStream = new FileInputStream(filePath);
    compareInputStreams(actualInputStream, expectedInputStream);
}

From source file:com.hp.autonomy.types.idol.GenerateIndexableXmlDocumentTest.java

@Test
public void generateFile() throws IOException {
    final Collection<String> numericFields = new ArrayList<>(1000);
    final Random random = new Random();
    for (int i = 0; i < 1000; i++) {
        numericFields.add(String.valueOf(1451610061 + random.nextInt(1000)));
    }//from   ww w . java2  s  . com

    final Collection<SampleDoc> sampleDocs = new ArrayList<>(numericFields.size());
    int i = 0;
    for (final String numericField : numericFields) {
        sampleDocs.add(new SampleDoc(UUID.randomUUID().toString(), "Sample Date Title " + i++,
                "Sample Date Content", numericField));
    }

    @SuppressWarnings("TypeMayBeWeakened")
    final DocumentGenerator<SampleDoc> documentGenerator = processorFactory
            .getDocumentGenerator(SampleDoc.class);
    final File outputFile = new File(TEST_DIR, "sampleFile.xml");
    FileUtils.writeStringToFile(outputFile,
            documentGenerator.generateIdolXmlIndexDocument(sampleDocs, StandardCharsets.UTF_8));
    assertTrue(outputFile.exists());
}

From source file:com.stratio.crossdata.connector.plugin.installer.InstallerGoalLauncher.java

public static void launchInstallerGoal(InstallerGoalConfig config, Log log) throws IOException {

    log.info("Create TARGET directory.");
    File targetDirectory = new File(
            FilenameUtils.concat(config.getOutputDirectory(), config.getConnectorName()));
    if (targetDirectory.exists()) {
        log.info("Remove previous TARGET directory");
        FileUtils.forceDelete(targetDirectory);
    }//from   ww  w.jav a  2 s.  c o  m
    File includeConfigDirectory = new File(config.getIncludeDirectory());
    FileUtils.copyDirectory(includeConfigDirectory, targetDirectory);

    log.info("Create LIB directory.");
    File libDirectory = new File(FilenameUtils.concat(targetDirectory.toString(), "lib"));
    FileUtils.copyFileToDirectory(config.getMainJarRepo(), libDirectory);
    for (File jarFile : config.getDependenciesJarRepo()) {
        FileUtils.copyFileToDirectory(jarFile, libDirectory);
    }

    log.info("Create CONF directory.");
    File confDirectory = new File(FilenameUtils.concat(targetDirectory.toString(), "conf"));
    File confConfigDirectory = new File(config.getConfigDirectory());
    FileUtils.copyDirectory(confConfigDirectory, confDirectory);

    log.info("Create BIN Directory");
    File binDirectory = new File(FilenameUtils.concat(targetDirectory.toString(), "bin"));
    FileUtils.forceMkdir(binDirectory);

    log.info("Launch template");
    String outputString = (config.getUnixScriptTemplate());
    outputString = outputString.replaceAll("<name>", config.getConnectorName());
    outputString = outputString.replaceAll("<desc>", config.getDescription());
    String user = config.getUserService();
    if (config.isUseCallingUserAsService()) {
        user = System.getProperty("user.name");
    }
    outputString = outputString.replaceAll("<user>", user);
    outputString = outputString.replaceAll("<mainClass>", config.getMainClass());
    int index = config.getMainClass().lastIndexOf('.');
    String className = config.getMainClass();
    if (index != -1) {
        className = config.getMainClass().substring(index + 1);
    }
    outputString = outputString.replaceAll("<mainClassName>", className);

    outputString = outputString.replaceAll("<jmxPort>", config.getJmxPort());
    String pidFileName = "";
    if (config.getPidFileName() != null) {
        pidFileName = config.getPidFileName();
    }
    outputString = outputString.replaceAll("<pidFileName>", pidFileName);

    File binFile = new File(FilenameUtils.concat(binDirectory.toString(), config.getConnectorName()));
    FileUtils.writeStringToFile(binFile, outputString);
    if (!binFile.setExecutable(true)) {
        throw new IOException("Can't change executable option.");
    }

    log.info("Process complete: " + targetDirectory);
}

From source file:com.gemstone.gemfire.management.internal.configuration.ZipUtilsJUnitTest.java

@Test
public void testZipUtils() throws Exception {
    File sf = new File(sourceFolderName);
    File cf = new File(FilenameUtils.concat(sourceFolderName, clusterFolderName));
    File gf = new File(FilenameUtils.concat(sourceFolderName, groupFolderName));
    sf.mkdir();/*from w  w w.j a v  a 2 s  .co m*/
    cf.mkdir();
    gf.mkdir();
    FileUtils.writeStringToFile(new File(FilenameUtils.concat(cf.getCanonicalPath(), clusterTextFileName)),
            clusterText);
    FileUtils.writeStringToFile(new File(FilenameUtils.concat(gf.getCanonicalPath(), groupTextFileName)),
            groupText);
    ZipUtils.zip(sourceFolderName, zipFileName);
    File zipFile = new File(zipFileName);
    assertTrue(zipFile.exists());
    assertTrue(zipFile.isFile());
    ZipUtils.unzip(zipFileName, destinationFolderName);

    File df = new File(destinationFolderName);
    assertTrue(df.exists());
    assertTrue(df.isDirectory());

    File[] subDirs = df.listFiles();
    assertTrue((subDirs != null) && (subDirs.length != 0));
    File dfClusterTextFile = new File(FilenameUtils.concat(destinationFolderName,
            clusterFolderName + File.separator + clusterTextFileName));
    File dfGroupTextFile = new File(
            FilenameUtils.concat(destinationFolderName, groupFolderName + File.separator + groupTextFileName));

    assertTrue(clusterText.equals(FileUtils.readFileToString(dfClusterTextFile)));
    assertTrue(groupText.equals(FileUtils.readFileToString(dfGroupTextFile)));
}

From source file:au.org.ala.spatial.analysis.layers.LayerDistanceIndex.java

/**
 * Get all available inter layer association distances.
 *
 * @return Map of all available distances as Map&ltString, Double&gt. The
 * key String is fieldId1 + " " + fieldId2 where fieldId1 &lt fieldId2.
 *///from   w ww .  j  a  v a 2s.c om
static public Map<String, Double> loadDistances() {
    Map<String, Double> map = new ConcurrentHashMap<String, Double>();
    BufferedReader br = null;
    try {
        File file = new File(IntersectConfig.getAlaspatialOutputPath() + LAYER_DISTANCE_FILE);

        //attempt to create empty file if it does not exist
        if (!new File(IntersectConfig.getAlaspatialOutputPath()).exists()) {
            new File(IntersectConfig.getAlaspatialOutputPath()).mkdirs();
        }
        if (!file.exists()) {
            FileUtils.writeStringToFile(file, "");
        }
        br = new BufferedReader(new FileReader(file));

        String line;
        while ((line = br.readLine()) != null) {
            if (line.length() > 0) {
                String[] keyvalue = line.split("=");
                double d = Double.NaN;
                try {
                    d = Double.parseDouble(keyvalue[1]);
                } catch (Exception e) {
                    logger.info("cannot parse value in " + line);
                }
                map.put(keyvalue[0], d);
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }

    return map;
}

From source file:cc.kave.episodes.mining.patterns.FrequenciesAnalyzer.java

public void analyzeSuperEpisodes(int numbRepos, int frequency, double entropy) throws IOException {
    Map<Integer, Set<Episode>> patterns = postprocessor.postprocess(numbRepos, frequency, entropy);
    StringBuilder sb = new StringBuilder();

    for (Map.Entry<Integer, Set<Episode>> entry : patterns.entrySet()) {
        if ((entry.getKey() < 2) || (entry.getKey() == patterns.size())) {
            continue;
        }//from  w w w  .  j a  va  2s  .  c om
        sb.append(entry.getKey() + "-node episodes\n");
        Logger.log("Analyzing for %d-node episodes ...", entry.getKey());
        for (Episode episode : entry.getValue()) {
            Set<Episode> superEpisodes = getSuperEpisodes(episode, patterns.get(entry.getKey() + 1));
            if (superEpisodes.size() > 0) {
                sb.append(episode.getFacts().toString() + "\t" + episode.getFrequency() + "\n");
                for (Episode sep : superEpisodes) {
                    sb.append(sep.getFacts().toString() + "\t" + sep.getFrequency() + "\n");
                }
            } else {
                continue;
            }
            sb.append("\n");
        }
        sb.append("\n");
    }
    FileUtils.writeStringToFile(getFilePath(numbRepos, frequency, entropy), sb.toString());
}