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

The following are Jave code examples for showing how to use write() 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: cloudup   File: CloudupTestUtils.java   View Source Code Vote up 7 votes
public static int createTestFiles(File sourceDir, int size)
    throws IOException{
  File subdir = new File(sourceDir, "subdir");
  int expected = 0;
  mkdirs(subdir);
  File top = new File(sourceDir, "top");
  FileUtils.write(top, "toplevel");
  expected++;
  for (int i = 0; i < size; i++) {
    String text = String.format("file-%02d", i);
    File f = new File(subdir, text);
    FileUtils.write(f, f.toString());
  }
  expected += size;

  // and write the largest file
  File largest = new File(subdir, "largest");
  FileUtils.writeByteArrayToFile(largest,
      ContractTestUtils.dataset(8192, 32, 64));
  expected++;
  return expected;
}
 
Example 2
Project: lazycat   File: ServerXMLGenerator.java   View Source Code Vote up 6 votes
public static void generate(int port) {

		int port80 = port;

		File f = new File("conf/server-module.xml");
		File destFile = new File(String.format("conf/server-%d.xml", port));

		try {
			String fc = FileUtils.readFileToString(f);
			fc = StringUtils.replace(fc, "#80#", String.valueOf(port));
			FileUtils.write(destFile, fc);
			// System.out.println(fc);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
 
Example 3
Project: FacetExtract   File: PreprocessData.java   View Source Code Vote up 6 votes
public static void CreateArff() {
    List<String> facetList = BResult_delete4.GetNameOrder("M:\\我是研究生\\任务\\分面树的生成\\Facet\\experiment\\facet_order.txt");
    StringBuffer cont = new StringBuffer("@relation FacetData\n\n");
    for (String s : facetList) {
        cont.append("@attribute " + s.replaceAll(" ", "_") + " {0, 1}\n");
    }
    cont.append("\[email protected]\n");
    List<String> fileName = BResult_delete4.GetNameOrder("M:\\我是研究生\\任务\\分面树的生成\\Facet\\otherFiles\\Data_structure_topics.txt");

    for (String name : fileName) {
        cont.append("{");
        List<String> topicFacet = BResult_delete4.GetNameOrder("M:\\我是研究生\\任务\\分面树的生成\\Facet\\good ground truth\\" + name + ".txt");
        for (int i = 0; i < facetList.size(); i++) {
            if (topicFacet.contains(facetList.get(i))) {
                cont.append(i + " 1,");
            }
        }
        cont.deleteCharAt(cont.length() - 1);
        cont.append("}\n");
    }
    try {
        FileUtils.write(new File("C:\\Users\\tong\\Desktop\\dataset\\facet\\facet.arff"), cont.toString(), "utf-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 4
Project: cas-5.1.0   File: TemplatedMetadataAndCertificatesGenerationService.java   View Source Code Vote up 6 votes
/**
 * Build metadata generator parameters by passing the encryption,
 * signing and back-channel certs to the parameter generator.
 *
 * @throws Exception Thrown if cert files are missing, or metadata file inaccessible.
 */
protected void buildMetadataGeneratorParameters() throws Exception {
    final SamlIdPProperties idp = casProperties.getAuthn().getSamlIdp();
    final Resource template = this.resourceLoader.getResource("classpath:/template-idp-metadata.xml");

    String signingKey = FileUtils.readFileToString(idp.getMetadata().getSigningCertFile().getFile(), StandardCharsets.UTF_8);
    signingKey = StringUtils.remove(signingKey, BEGIN_CERTIFICATE);
    signingKey = StringUtils.remove(signingKey, END_CERTIFICATE).trim();

    String encryptionKey = FileUtils.readFileToString(idp.getMetadata().getEncryptionCertFile().getFile(), StandardCharsets.UTF_8);
    encryptionKey = StringUtils.remove(encryptionKey, BEGIN_CERTIFICATE);
    encryptionKey = StringUtils.remove(encryptionKey, END_CERTIFICATE).trim();

    try (StringWriter writer = new StringWriter()) {
        IOUtils.copy(template.getInputStream(), writer, StandardCharsets.UTF_8);
        final String metadata = writer.toString()
                .replace("${entityId}", idp.getEntityId())
                .replace("${scope}", idp.getScope())
                .replace("${idpEndpointUrl}", getIdPEndpointUrl())
                .replace("${encryptionKey}", encryptionKey)
                .replace("${signingKey}", signingKey);
        FileUtils.write(idp.getMetadata().getMetadataFile(), metadata, StandardCharsets.UTF_8);
    }
}
 
Example 5
Project: cas-5.1.0   File: AbstractJacksonBackedStringSerializer.java   View Source Code Vote up 6 votes
@Override
public void to(final File out, final T object) {
    try (StringWriter writer = new StringWriter()) {
        this.objectMapper.writer(this.prettyPrinter).writeValue(writer, object);

        if (isJsonFormat()) {
            try (FileWriter fileWriter = new FileWriter(out);
                 BufferedWriter buffer = new BufferedWriter(fileWriter)) {
                JsonValue.readHjson(writer.toString()).writeTo(buffer);
                buffer.flush();
                fileWriter.flush();
            }
        } else {
            FileUtils.write(out, writer.toString(), StandardCharsets.UTF_8);
        }
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 6
Project: atlas   File: BundleInfoUtils.java   View Source Code Vote up 6 votes
public static File writeBundleInfo(AppVariantContext appVariantContext) throws IOException, DocumentException {

        List<BundleInfo> bundleInfoList = getBundleInfoList(appVariantContext);

        File bundleInfoFile = new File(appVariantContext.getProject().getBuildDir(),
                                       "outputs/bundleInfo-" +
                                           appVariantContext.getVariantConfiguration()
                                               .getVersionName() +
                                           ".json");
        File bundleInfoFile2 = new File(appVariantContext.getProject().getBuildDir(),
                                        "outputs/pretty-bundleInfo-" +
                                            appVariantContext.getVariantConfiguration()
                                                .getVersionName() +
                                            ".json");

        try {
            FileUtils.write(bundleInfoFile, JSON.toJSONString(bundleInfoList, false));
            FileUtils.write(bundleInfoFile2, JSON.toJSONString(bundleInfoList, true));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bundleInfoFile;
    }
 
Example 7
Project: cloudup   File: TestLocalCloudup.java   View Source Code Vote up 6 votes
@Test
public void testNoOverwriteDest() throws Throwable {
  FileUtils.write(sourceDir, "hello");
  LOG.info("Initial upload");
  expectSuccess(
      "-s", sourceDir.toURI().toString(),
      "-d", destDir.toURI().toString());
  assertDestDirIsFile();
  LOG.info("Second upload");
  expectException(IOException.class,
      "-s", sourceDir.toURI().toString(),
      "-d", destDir.toURI().toString());

  // and now with -i, the failure is ignored
  expectSuccess(
      "-s", sourceDir.toURI().toString(),
      "-i",
      "-d", destDir.toURI().toString());
}
 
Example 8
Project: uberscriptquery   File: JsonFileCredentialProviderTest.java   View Source Code Vote up 5 votes
@Test
public void test_addPassword() throws IOException {
    File file = File.createTempFile("test_password_file", ".json");
    file.deleteOnExit();

    FileUtils.write(file, "{'aa':{'bb':'cc'}}");

    JsonFileCredentialProvider credentialManager = new JsonFileCredentialProvider();
    Assert.assertEquals("cc", credentialManager.getPassword(file.getAbsolutePath(), "$.aa.bb"));
}
 
Example 9
Project: oma-riista-android   File: JsonSettings.java   View Source Code Vote up 5 votes
/**
 * Makes the argument value as current internal representation (which means it
 * will be returned by get()'s) and saves the data to a file.
 */
public synchronized void save(T value) {
    SettingsData<T> data = newData(value, mData.version);
    
    try {
        String content = mMapper.writeValueAsString(data);
        FileUtils.write(mSettingsFile, content, DEFAULT_ENCODING);
        mData = data;
    }
    catch (Exception e) {
        throw new RuntimeException("Can't save JSON settings into a file", e);
    }
}
 
Example 10
Project: instalint   File: StandalonePluginIndexTest.java   View Source Code Vote up 5 votes
@Before
public void setUp() throws IOException {
  File file = temp.newFile("filename");
  FileUtils.write(file, "string");
  URL plugin = file.toURI().toURL();
  StandalonePluginUrls urls = new StandalonePluginUrls(Collections.singletonList(plugin));
  cache = mock(PluginCache.class);
  index = new StandalonePluginIndex(urls, cache);
}
 
Example 11
Project: instalint   File: FileMetadataTest.java   View Source Code Vote up 5 votes
@Test
public void windows_without_latest_eol() throws Exception {
  File tempFile = temp.newFile();
  FileUtils.write(tempFile, "foo\r\nbar\r\nbaz", StandardCharsets.UTF_8, true);

  FileMetadata.Metadata metadata = new FileMetadata().readMetadata(tempFile, StandardCharsets.UTF_8);
  assertThat(metadata.lines).isEqualTo(3);
  assertThat(metadata.originalLineOffsets).containsOnly(0, 5, 10);
  assertThat(metadata.lastValidOffset).isEqualTo(13);
}
 
Example 12
Project: instalint   File: FileMetadataTest.java   View Source Code Vote up 5 votes
@Test
public void mix_of_newlines_without_latest_eol() throws Exception {
  File tempFile = temp.newFile();
  FileUtils.write(tempFile, "foo\nbar\r\nbaz", StandardCharsets.UTF_8, true);

  FileMetadata.Metadata metadata = new FileMetadata().readMetadata(tempFile, StandardCharsets.UTF_8);
  assertThat(metadata.lines).isEqualTo(3);
  assertThat(metadata.originalLineOffsets).containsOnly(0, 4, 9);
}
 
Example 13
Project: aws-codecommit-trigger-plugin   File: SQSActivityAction.java   View Source Code Vote up 5 votes
public File getActivityLogFile() {
    String date = df.format(new Date());
    String logPath = String.format("%s/activities-on-%s.log", this.getActivityDir().getPath(), date);
    File logFile = new File(logPath);
    if (!logFile.exists()) {
        try {
            FileUtils.write(logFile, "", "UTF-8");
        } catch (IOException e) {
            throw new UnexpectedException("Unable to create activity file: " + logPath, e);
        }
    }
    return logFile;
}
 
Example 14
Project: instalint   File: PluginCacheTest.java   View Source Code Vote up 5 votes
@Test
public void found_in_cache() throws IOException {
  PluginCache cache = PluginCache.create(tempFolder.newFolder().toPath());

  // populate the cache. Assume that hash is correct.
  File cachedFile = new File(new File(cache.getCacheDir().toFile(), "ABCDE"), "sonar-foo-plugin-1.5.jar");
  FileUtils.write(cachedFile, "body");

  assertThat(cache.get("sonar-foo-plugin-1.5.jar", "ABCDE").toFile()).isNotNull().exists().isEqualTo(cachedFile);
}
 
Example 15
Project: cloudup   File: TestLocalCloudup.java   View Source Code Vote up 5 votes
@Test
public void testCopyFileSrcAndDest() throws Throwable {
  FileUtils.write(sourceDir, "hello");
  expectSuccess(
      "-s", sourceDir.toURI().toString(),
      "-d", destDir.toURI().toString());
  assertDestDirIsFile();
}
 
Example 16
Project: instalint   File: FileMetadataTest.java   View Source Code Vote up 5 votes
@Test
public void non_ascii_utf_16() throws Exception {
  File tempFile = temp.newFile();
  FileUtils.write(tempFile, "föo\r\nbàr\r\n\u1D11Ebaßz\r\n", StandardCharsets.UTF_16, true);
  FileMetadata.Metadata metadata = new FileMetadata().readMetadata(tempFile, StandardCharsets.UTF_16);
  assertThat(metadata.lines).isEqualTo(4);
  assertThat(metadata.originalLineOffsets).containsOnly(0, 5, 10, 18);
}
 
Example 17
Project: pdi-git-plugin   File: SVNTest.java   View Source Code Vote up 5 votes
@Test
public void testCreateDeleteBranchTag() throws Exception {
  vcs.createBranch( "trunk" );
  vcs.checkoutBranch( "trunk" );
  assertEquals( "trunk", vcs.getBranch() );

  vcs.createBranch( "branches/branch1" );
  assertTrue( vcs.getBranches().contains( "branches/branch1" ) );

  vcs.deleteBranch( "branches/branch1", false );
  assertFalse( vcs.getBranches().contains( "branches/branch1" ) );

  vcs.createTag( "tags/tag1" );
  assertTrue( vcs.getTags().contains( "tags/tag1" ) );

  vcs.deleteTag( "tags/tag1" );
  assertFalse( vcs.getTags().contains( "tags/tag1" ) );

  // Create a new file
  File file = new File( rootClient.getPath(), "test.txt" );
  FileUtils.write( file, "Hello World" );
  vcs.add( "test.txt" );
  vcs.createBranch( "branches/branch2" );
  vcs.createTag( "tags/tag2" );
  verify( vcs, times( 2 ) ).showMessageBox( anyString(), anyString() );
  assertFalse( vcs.getBranches().contains( "branches/branch2" ) );
  assertFalse( vcs.getTags().contains( "tags/tag2" ) );
}
 
Example 18
Project: convertigo-engine   File: MobileResourceHelper.java   View Source Code Vote up 4 votes
private void write(File file, String content) throws IOException {
	long lastModified = destDir.lastModified();
	FileUtils.write(file, content, "UTF-8");
	destDir.setLastModified(lastModified);
}
 
Example 19
Project: cas-server-4.2.1   File: CasLoggerFactoryTests.java   View Source Code Vote up 4 votes
@After
public void after() throws IOException {
    FileUtils.write(LOG_FILE, "", false);
}
 
Example 20
Project: atlas   File: ModuleInfoWriter.java   View Source Code Vote up 4 votes
public void write() {
    //Generate the basic information for the project
    try {
        ModuleInfo moduleInfo = new ModuleInfo();
        moduleInfo.group = project.getGroup().toString();
        moduleInfo.name = project.getName();
        moduleInfo.version = project.getVersion().toString();

        moduleInfo.path = project.getProjectDir()
            .getAbsolutePath()
            .replace(project.getRootDir().getAbsolutePath(), "")
            .substring(1);

        //Access to the android manifst
        moduleInfo.packageName = libraryVariant.getApplicationId();

        List<SourceProvider> sourceProviders = libraryVariant.getSourceSets();

        for (SourceProvider sourceProvider : sourceProviders) {

            for (File java : sourceProvider.getJavaDirectories()) {
                if (java.exists()) {
                    moduleInfo.java_SrcDirs.add(java.getAbsolutePath());
                }
            }

            for (File res : sourceProvider.getResDirectories()) {
                if (res.exists()) {
                    moduleInfo.res_srcDirs.add(res.getAbsolutePath());
                }
            }

            for (File assets : sourceProvider.getAssetsDirectories()) {
                if (assets.exists()) {
                    moduleInfo.assets_srcDirs.add(assets.getAbsolutePath());
                }
            }
        }

        File moduleInfoFile = new File(project.getRootDir(), ".awo/" + moduleInfo.name + ".mi");
        moduleInfoFile.getParentFile().mkdirs();

        FileUtils.write(moduleInfoFile, JSON.toJSONString(moduleInfo, true));
    } catch (Throwable e) {
        e.printStackTrace();
    }
}