Java Code Examples for org.apache.commons.io.FileUtils.writeStringToFile()

The following are Jave code examples for showing how to use writeStringToFile() of the org.apache.commons.io.FileUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: MicroServiceProject   File: IterativeRecommender.java   View Source Code Vote up 8 votes
public void outputToFile(int iter, Map<Measure, Double> measures){
	File evalFile = new File("./demo/Results/"+algoName+".txt");
	for (int i=0;i<iterArray.length;i++) {
		if (iter==iterArray[i]) {
			String result = getEvalInfo(measures);
			// double commas as the separation of results and configuration
			StringBuilder sb = new StringBuilder();
			String config = toString();
			sb.append(algoName).append(",").append(result).append(",,");
			if (!config.isEmpty())
				sb.append(config).append(",").append(iter);
			String evalInfo = sb.toString();

			try {
				FileUtils.writeStringToFile(evalFile,evalInfo+"\n",true);
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println(iter);
			System.out.println(evalInfo);

		}
	}
}
 
Example 2
Project: jwala   File: ManagedJvmBuilder.java   View Source Code Vote up 7 votes
protected void createServerXml() {
    final String tomcatConfDir = getTomcatStagingDir().getAbsolutePath() + "/conf";

    if (ifGroupServerXmlExists()) {
        //return, one will be created as a resource
        return;
    }

    String generatedText = generateServerXml();

    LOGGER.debug("Saving template to {}", tomcatConfDir + "/" + SERVER_XML);

    File templateFile = new File(tomcatConfDir + "/" + SERVER_XML);

    try {
        FileUtils.writeStringToFile(templateFile, generatedText, Charset.forName("UTF-8"));
    } catch (IOException e) {
        throw new JvmServiceException(e);
    }
}
 
Example 3
Project: Babler   File: LogDB.java   View Source Code Vote up 6 votes
/**
 * Checks if a post was already save
 * @param id the ID of the post
 * @param lang the languageCode of the post
 * @return true for new posts
 */

public static boolean isNew(String id, String lang){

    File f = new File(SCRAPING_FOLDER+lang+LOG_FILE);
    if(f.exists())
        return !find(f,id);
    else {
        try {
            FileUtils.writeStringToFile(f, "id: 1,url:www.test.com\n");
            return true;
        } catch (IOException e) {
            log.error(e);
        }
    }
    return true;

}
 
Example 4
Project: pdi-git-plugin   File: UIGitTest.java   View Source Code Vote up 6 votes
@Test
public void testPull() throws Exception {
  // source: db2, target: db
  setupRemote();
  Git git2 = new Git( db2 );

  // put some file in the source repo and sync
  File sourceFile = new File( db2.getWorkTree(), "SomeFile.txt" );
  FileUtils.writeStringToFile( sourceFile, "Hello world" );
  git2.add().addFilepattern( "SomeFile.txt" ).call();
  git2.commit().setMessage( "Initial commit for source" ).call();
  PullResult pullResult = git.pull().call();

  // change the source file
  FileUtils.writeStringToFile( sourceFile, "Another change" );
  git2.add().addFilepattern( "SomeFile.txt" ).call();
  git2.commit().setMessage( "Some change in remote" ).call();
  git2.close();

  assertTrue( uiGit.pull() );
}
 
Example 5
Project: Habanero   File: JSONReportMerger.java   View Source Code Vote up 6 votes
/**
 * merge source file into target
 *
 * @param target
 * @param source
 */
public void mergeFiles(File target, File source) throws Throwable {
    String targetReport = FileUtils.readFileToString(target);
    String sourceReport = FileUtils.readFileToString(source);

    JSONParser jp = new JSONParser();

    try {
        JSONArray parsedTargetJSON = (JSONArray) jp.parse(targetReport);
        JSONArray parsedSourceJSON = (JSONArray) jp.parse(sourceReport);
        // Merge two JSON reports
        parsedTargetJSON.addAll(parsedSourceJSON);
        // this is a new writer that adds JSON indentation.
        Writer writer = new JSONWriter();
        // convert our parsedJSON to a pretty form
        parsedTargetJSON.writeJSONString(writer);
        // and save the pretty version to disk
        FileUtils.writeStringToFile(target, writer.toString());
    } catch (ParseException pe) {
        pe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 6
Project: gaffer-doc   File: PropertiesWalkthroughRunner.java   View Source Code Vote up 6 votes
@Override
protected void _generate() throws Exception {
    FileUtils.writeStringToFile(
            new File(outputPath + toMdFileName("contents")),
            getTableOfContents()
    );
    FileUtils.writeStringToFile(
            new File(outputPath + toMdFileName("introduction")),
            getIntro()
    );
    FileUtils.writeStringToFile(
            new File(outputPath + toMdFileName("Simple Properties")),
            getSimpleProperties()
    );
    FileUtils.writeStringToFile(
            new File(outputPath + toMdFileName("Sketches")),
            getSketches()
    );
    FileUtils.writeStringToFile(
            new File(outputPath + toMdFileName("Timestamps")),
            getTimestamps()
    );

    generateWalkthroughs();
    generateSimpleProperties();
}
 
Example 7
Project: ProjektGG   File: ErrorUtils.java   View Source Code Vote up 5 votes
/**
 * Writes a crash log to the crash log file.
 * 
 * @param e
 *            The exception.
 * @param forceExit
 *            Whether the application should get shut down.
 */
public static void writeCrashLogToFile(Exception e, boolean forceExit) {
	try {
		FileUtils.writeStringToFile(CRASH_LOG_FILE,
				e.getLocalizedMessage());
	} catch (IOException e1) {
		e1.printStackTrace();
	}

	if (forceExit)
		System.exit(-1);
}
 
Example 8
Project: Reer   File: TestFile.java   View Source Code Vote up 5 votes
public TestFile write(Object content) {
    try {
        FileUtils.writeStringToFile(this, content.toString());
    } catch (IOException e) {
        throw new RuntimeException(String.format("Could not write to test file '%s'", this), e);
    }
    return this;
}
 
Example 9
Project: Babler   File: LogDB.java   View Source Code Vote up 5 votes
public void logWithUrlNonStatic(String id, String url, String lang){
    try {
        File f = dbFile;
        FileUtils.writeStringToFile(f, "id: " +id+ ", url:"+url+"\n",true);
        LogDBEntry entry = new LogDBEntry(id,url);
        db.put(entry.getId(),entry);

    } catch (IOException e) {
        log.error(e);
    }

}
 
Example 10
Project: Biliomi   File: RaffleLogFile.java   View Source Code Vote up 5 votes
private void write(String data) {
  try {
    FileUtils.writeStringToFile(logFile, data + Character.LINE_SEPARATOR, "UTF-8", true);
  } catch (IOException e) {
    LogManager.getLogger(getClass()).error("Failed writing to raffle log", e);
  }
}
 
Example 11
Project: carnotzet   File: MavenDependencyResolver.java   View Source Code Vote up 5 votes
private void writeDotConfigCache() {
	Path userConfigFolder = getUserConfigFolder();
	if (!userConfigFolder.toFile().exists()) {
		if (!userConfigFolder.toFile().mkdirs()) {
			throw new CarnotzetDefinitionException("Could not create directory [" + userConfigFolder + "]");
		}
	}
	Path localRepoPathCache = userConfigFolder.resolve("m2LocalRepoPath");
	try {
		FileUtils.writeStringToFile(localRepoPathCache.toFile(), this.localRepoPath.toString(), "UTF-8");
	}
	catch (IOException e) {
		log.warn("Could not write file [{}]", localRepoPathCache);
	}
}
 
Example 12
Project: Cognizant-Intelligent-Test-Scripter   File: CMProjectCreator.java   View Source Code Vote up 5 votes
private void copyClassPath(File location) {
    try {
        String content = FileUtils.readFileToString(dotClassPath, Charset.defaultCharset());
        content = content.replace("</classpath>", enginePath + "</classpath>");
        content = content.replace("..", new File("").getAbsolutePath());
        File classFile = new File(location, dotClassPath.getName());
        FileUtils.writeStringToFile(classFile, content, Charset.defaultCharset());
    } catch (IOException ex) {
        Logger.getLogger(CMProjectCreator.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 13
Project: gaffer-doc   File: PropertiesWalkthroughRunner.java   View Source Code Vote up 5 votes
private void generateWalkthroughs(final List<AbstractWalkthrough> examples) throws Exception {
    for (final AbstractWalkthrough example : examples) {
        DocUtil.clearCache();
        FileUtils.writeStringToFile(
                new File(outputPath + toFolderName(WALKTHROUGHS_TITLE) + toMdFileName(example.getHeader())),
                example.walkthrough());
    }
}
 
Example 14
Project: gaffer-doc   File: ExampleDocRunner.java   View Source Code Vote up 5 votes
public void _generate() throws Exception {
    FileUtils.writeStringToFile(
            new File(outputPath + toMdFileName("contents")),
            getTableOfContents()
    );
    for (final Example example : examples) {
        DocUtil.clearCache();
        example.run();
        FileUtils.writeStringToFile(
                new File(outputPath + toMdFileName(example.getClass().getSimpleName().replace("Example", ""))),
                example.getOutput());
    }
}
 
Example 15
Project: Lahiya   File: LahiyaTestCaseReport.java   View Source Code Vote up 5 votes
public void generateReport(String packageName,List<String> flagList) throws IOException
{

    URL testClassesURL = Paths.get("target/test-classes").toUri().toURL();

    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{testClassesURL},
            ClasspathHelper.staticClassLoader());

    reflections = new Reflections(new ConfigurationBuilder()
            .setUrls(ClasspathHelper.forPackage(packageName,classLoader))
            .addClassLoader(classLoader)
            .filterInputsBy(new FilterBuilder().includePackage(packageName))
            .setScanners(new MethodAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner())
    );


    List<Map<String, TestClass>> list = new ArrayList<>();

    for (String flag : flagList)
    {
        list.add(printMethods(flag));
    }

    Gson gson = new Gson();
    String overviewTemplate = IOUtils.toString(getClass().getResourceAsStream("/index.tpl.html"));


    String editedTemplate = overviewTemplate.replace("##TEST_DATA##", gson.toJson(list));

    FileUtils.writeStringToFile(new File("target/test-list-html-report/index.html"), editedTemplate);
    logger.info("report file generated");
}
 
Example 16
Project: butterfly   File: ButterflyCliApp.java   View Source Code Vote up 5 votes
private static void writeResultFile(ButterflyCliRun run) {
    GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting();
    Gson gson = gsonBuilder.create();
    String runJsonString = gson.toJson(run);
    File resultFile = (File) optionSet.valueOf(CLI_OPTION_RESULT_FILE);
    try {
        FileUtils.writeStringToFile(resultFile, runJsonString, Charset.defaultCharset());
    } catch (IOException e) {
        logger.error("Error when writing CLI result file", e);
    }
}
 
Example 17
Project: shabdiz   File: MavenBasedColdManagerTest.java   View Source Code Vote up 5 votes
private void initLocalTestFile() throws IOException {

        test_file = File.createTempFile("test", ".txt");
        FileUtils.writeStringToFile(test_file, "Some text");
    }
 
Example 18
Project: atlas   File: ApBuildTask.java   View Source Code Vote up 5 votes
private static File getApkFiles(File outputDir,
                                AppVariantContext appVariantContext) throws IOException {

    File apkFiles = new File(outputDir, ApContext.APK_FILE_LIST);
    FileUtils.writeStringToFile(apkFiles,
                                JSON.toJSONString(appVariantContext.getApkFiles().finalApkFileList));
    return apkFiles;
}
 
Example 19
Project: karate   File: UploadController.java   View Source Code Vote up 5 votes
@PostMapping
public @ResponseBody FileInfo upload(@RequestParam("myFile") MultipartFile file, 
        @RequestParam("message") String message) throws Exception {
    String uuid = UUID.randomUUID().toString();
    String filePath = FILES_BASE + uuid;
    FileUtils.copyToFile(file.getInputStream(), new File(filePath));
    String filename = file.getOriginalFilename();
    String contentType = file.getContentType();
    FileInfo fileInfo = new FileInfo(uuid, filename, message, contentType);
    String json = mapper.writeValueAsString(fileInfo);
    FileUtils.writeStringToFile(new File(filePath + "_meta.txt"), json, "utf-8");
    return fileInfo;
}
 
Example 20
Project: circus-train   File: IntegrationTestHelper.java   View Source Code Vote up 4 votes
void createUnpartitionedTable(URI sourceTableUri) throws Exception {
  File dataFile = new File(sourceTableUri.getPath(), PART_00000);
  FileUtils.writeStringToFile(dataFile, "1\tadam\tlondon\n2\tsusan\tmilan\n");

  TestUtils.createUnpartitionedTable(metaStoreClient, DATABASE, SOURCE_UNPARTITIONED_TABLE, sourceTableUri);
}