Java Code Examples for java.nio.file.Files#write()

The following examples show how to use java.nio.file.Files#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CopyOrMoveTest.java    From copybara with Apache License 2.0 7 votes vote down vote up
@Test
public void testMoveOverwrite() throws Exception {
  CopyOrMove mover = skylark.eval("m", "m = "
      + "core.move("
      + "    before = 'foo',"
      + "    after = 'bar',"
      + "    overwrite = True,"
      + ")");
  Files.write(checkoutDir.resolve("foo"), "foo".getBytes(UTF_8));
  Files.write(checkoutDir.resolve("bar"), "bar".getBytes(UTF_8));
  transform(mover);

  assertThatPath(checkoutDir)
      .containsFile("bar", "foo")
      .containsNoMoreFiles();
  assertThrows(NonReversibleValidationException.class, () -> mover.reverse());
}
 
Example 2
Source File: NamedTemporaryDirectoryTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testSubdirectoriesAreDeleted() throws IOException {
  Path root;
  Path subdir;
  Path path;
  try (NamedTemporaryDirectory temp = new NamedTemporaryDirectory("prefix")) {
    root = temp.getPath();
    subdir = root.resolve("subdir");
    Files.createDirectories(subdir);
    path = subdir.resolve("some.file");
    Files.write(path, "data".getBytes(Charsets.UTF_8));
    Files.write(subdir.resolve("other"), "data".getBytes(Charsets.UTF_8));
    Files.write(root.resolve("other"), "data".getBytes(Charsets.UTF_8));
  }
  assertFalse(Files.exists(path));
  assertFalse(Files.exists(subdir));
  assertFalse(Files.exists(root));
}
 
Example 3
Source File: ToolBox.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A method for creating a jar's manifest file with supplied data.
 */
public static void mkManifestWithClassPath(String mainClass,
        String... classes) throws IOException {
    List <String> lines = new ArrayList<>();

    StringBuilder sb = new StringBuilder("Class-Path: ".length() +
            classes[0].length()).append("Class-Path: ").append(classes[0]);
    for (int i = 1; i < classes.length; i++) {
        sb.append(" ").append(classes[i]);
    }
    lines.add(sb.toString());
    if (mainClass != null) {
        lines.add(new StringBuilder("Main-Class: ".length() +
                  mainClass.length())
                  .append("Main-Class: ")
                  .append(mainClass).toString());
    }
    Files.write(Paths.get("MANIFEST.MF"), lines, null);
}
 
Example 4
Source File: SkylarkProjectBuildFileParserTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void canUseBuiltInListFunctionInExtension() throws Exception {
  Path directory = projectFilesystem.resolve("src").resolve("test");
  Files.createDirectories(directory);
  Path buildFile = directory.resolve("BUCK");
  Path extensionFile = directory.resolve("build_rules.bzl");
  Files.write(
      buildFile,
      Arrays.asList("load('//src/test:build_rules.bzl', 'guava_jar')", "guava_jar(name='foo')"));
  Files.write(
      extensionFile,
      Arrays.asList(
          "def guava_jar(name):",
          "  native.prebuilt_jar(name=name, binary_jar='foo.jar', licenses=list(('l1', 'l2')))"));
  Map<String, Object> rule = getSingleRule(buildFile);
  assertThat(
      Type.STRING_LIST.convert(rule.get("licenses"), "license"),
      equalTo(ImmutableList.of("l1", "l2")));
}
 
Example 5
Source File: GerritEndpointTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
  workdir = Jimfs.newFileSystem().getPath("/");
  TestingConsole console = new TestingConsole();
  OptionsBuilder options = new OptionsBuilder();
  options.setConsole(console).setOutputRootToTmpDir();
  dummyTrigger = new DummyTrigger();
  options.testingOptions.feedbackTrigger = dummyTrigger;
  options.testingOptions.checker = new DummyChecker(ImmutableSet.of("badword"));
  gitUtil = new GitTestUtil(options);
  Path credentialsFile = Files.createTempFile("credentials", "test");
  Files.write(credentialsFile, BASE_URL.getBytes(UTF_8));
  GitRepository repo = newBareRepo(Files.createTempDirectory("test_repo"),
      getGitEnv(), /*verbose=*/true, DEFAULT_TIMEOUT, /*noVerify=*/ false)
      .init()
      .withCredentialHelper("store --file=" + credentialsFile);
  gitUtil.mockRemoteGitRepos(new Validator(), repo);

  url = BASE_URL + "/foo/bar";
  options.general.starlarkMode = "STRICT";
  skylark = new SkylarkTestExecutor(options);
}
 
Example 6
Source File: RansacFilterClientTest.java    From render with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSingleSetRun()
        throws Exception {

    testDirectory = MipmapClientTest.createTestDirectory("ransac_filter_test_single");
    final File candidateFile = new File(testDirectory, "candidate_matches.json");
    Files.write(candidateFile.toPath(), CANDIDATE_MATCHES.getBytes());

    final String argString =
            "--matchRod 0.95 --matchModelType AFFINE --matchIterations 1000 --matchMaxEpsilon 10.0 --matchMinInlierRatio 0.0 " +
            "--matchMaxTrust 2.0 --matchFilter SINGLE_SET " +
            "--candidateFile \"" + candidateFile.getAbsolutePath() + "\" " +
            "--outputDirectory \"" + testDirectory.getAbsolutePath() + "\"";

    final RansacFilterClient.Parameters clientParameters = new RansacFilterClient.Parameters();
    clientParameters.parse(argString.split(" "));

    final RansacFilterClient client = new RansacFilterClient(clientParameters);
    client.run();

    validateResults(new int[] {185, 82, 181});
}
 
Example 7
Source File: JavaLanguage.java    From MSPaintIDE with MIT License 5 votes vote down vote up
private Consumer<String> bindFileVariable(Path input, Path output, String variableName) {
    var fileVariables = this.replaceData.computeIfAbsent(input.toString(), i -> new HashMap<>());
    return newValue -> {
        try {
            fileVariables.put(variableName, newValue);
            String[] content = {new String(Files.readAllBytes(input))};
            fileVariables.forEach((variable, value) -> content[0] = content[0].replace("%" + variable + "%", value));
            Files.write(output, content[0].getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
        } catch (IOException e) {
            LOGGER.error("There was a problem writing to " + output.toString(), e);
        }
    };
}
 
Example 8
Source File: SkylarkProjectBuildFileParserTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void readConfigFunction() throws Exception {
  Path buildFile = projectFilesystem.resolve("BUCK");
  Files.write(
      buildFile,
      Collections.singletonList(
          "prebuilt_jar(name=read_config('app', 'name', 'guava'), binary_jar='foo.jar')"));
  Map<String, Object> rule = getSingleRule(buildFile);
  assertThat(rule.get("name"), equalTo("guava"));
}
 
Example 9
Source File: SocketServer.java    From FuzzDroid with Apache License 2.0 5 votes vote down vote up
private void handleDexFileReceived(DexFileTransferTraceItem dexFileRequest) {
	byte[] dexFile = dexFileRequest.getDexFile();
	try{
		// Write the received dex file to disk for debugging
		long timestamp = System.currentTimeMillis();
		String dirPath = String.format("%s/dexFiles/", UtilInstrumenter.SOOT_OUTPUT);
		File dir = new File(dirPath);
		if(!dir.exists())
			dir.mkdir();
		String filePath = String.format("%s/dexFiles/%d_dexfile.dex", UtilInstrumenter.SOOT_OUTPUT, timestamp);
		System.out.println(String.format("Dex-File: %s (code position: %d)", filePath,
				dexFileRequest.getLastExecutedStatement()));
		LoggerHelper.logEvent(MyLevel.DEXFILE, String.format("Received dex-file %s/dexFiles/%d_dexfile.dex", UtilInstrumenter.SOOT_OUTPUT, timestamp));
		Files.write(Paths.get(filePath), dexFile);
		
		// We need to remove the statements that load the external code,
		// because we merge it into a single app. We must not take the
		// last executed statement, but the current one -> +1.
		CodePosition codePos = decisionMaker.getCodePositionManager()
				.getCodePositionByID(dexFileRequest
						.getLastExecutedStatement());
		Unit codePosUnit = decisionMaker.getCodePositionManager().getUnitForCodePosition(codePos);
		
		Set<InstanceIndependentCodePosition> statementsToRemove = new HashSet<>();
		statementsToRemove.add(new InstanceIndependentCodePosition(codePos.getEnclosingMethod(),
				codePos.getLineNumber(), codePosUnit.toString()));
		
		// Register the new dex file and spawn an analysis task for it
		DexFile dexFileObj = decisionMaker.getDexFileManager().add(new DexFile(
				dexFileRequest.getFileName(), filePath, dexFile));
		AnalysisTaskManager taskManager = decisionMaker.getAnalysisTaskManager();
		taskManager.enqueueAnalysisTask(taskManager.getCurrentTask().deriveNewTask(dexFileObj,
				statementsToRemove));
	}catch(Exception ex) {
		ex.printStackTrace();
	}
	System.out.println("received dex file");
}
 
Example 10
Source File: TestFetchFile.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testMoveAndKeep() throws IOException {
    final File sourceFile = new File("target/1.txt");
    final byte[] content = "Hello, World!".getBytes();
    Files.write(sourceFile.toPath(), content, StandardOpenOption.CREATE);

    final TestRunner runner = TestRunners.newTestRunner(new FetchFile());
    runner.setProperty(FetchFile.FILENAME, sourceFile.getAbsolutePath());
    runner.setProperty(FetchFile.COMPLETION_STRATEGY, FetchFile.COMPLETION_MOVE.getValue());
    runner.assertNotValid();
    runner.setProperty(FetchFile.MOVE_DESTINATION_DIR, "target/move-target");
    runner.setProperty(FetchFile.CONFLICT_STRATEGY, FetchFile.CONFLICT_KEEP_INTACT.getValue());
    runner.assertValid();

    final File destDir = new File("target/move-target");
    final File destFile = new File(destDir, sourceFile.getName());

    final byte[] goodBye = "Good-bye".getBytes();
    Files.write(destFile.toPath(), goodBye);

    runner.enqueue(new byte[0]);
    runner.run();
    runner.assertAllFlowFilesTransferred(FetchFile.REL_SUCCESS, 1);
    runner.getFlowFilesForRelationship(FetchFile.REL_SUCCESS).get(0).assertContentEquals(content);

    final byte[] replacedContent = Files.readAllBytes(destFile.toPath());
    assertTrue(Arrays.equals(goodBye, replacedContent));
    assertFalse(sourceFile.exists());
    assertTrue(destFile.exists());
}
 
Example 11
Source File: JUnitGradeSheetListener.java    From public with Apache License 2.0 5 votes vote down vote up
private void writeToFile(final String text) {
    try {
        Files.write(outputPath, text.getBytes(StandardCharsets.UTF_8));
    } catch (final IOException e) {
        throw new AssertionError("IO error while writing to file.", e);
    }
}
 
Example 12
Source File: SecurityTools.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void setResponse(String... responses) throws IOException {
    String text;
    if (responses.length > 0) {
        text = Stream.of(responses).collect(
                Collectors.joining("\n", "", "\n"));
    } else {
        text = "";
    }
    Files.write(Paths.get(RESPONSE_FILE), text.getBytes());
}
 
Example 13
Source File: GitDestinationTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
private GitRepository checkCredentials() throws IOException, RepoException, ValidationException {
  Path credentialsFile = Files.createTempFile("credentials", "test");
  Files.write(credentialsFile, "https://user:[email protected]".getBytes(UTF_8));
  options.git.credentialHelperStorePath = credentialsFile.toString();

  GitRepository repository = destinationFirstCommit().getLocalRepo().load(console);
  UserPassword result = repository
      .credentialFill("https://somehost.com/foo/bar");

  assertThat(result.getUsername()).isEqualTo("user");
  assertThat(result.getPassword_BeCareful()).isEqualTo("SECRET");
  return repository;
}
 
Example 14
Source File: DefaulExecutable.java    From git-code-format-maven-plugin with MIT License 5 votes vote down vote up
@Override
public Executable appendCommandCall(String commandCall) throws IOException {
  String unixCommandCall = unixifyPath(commandCall, true);
  boolean callExists =
      Files.readAllLines(file).stream().anyMatch(s -> s.contains(unixCommandCall));
  if (callExists) {
    log.get().debug("Command call already exists in " + file);
  } else {
    log.get().debug("No command call found in " + file);
    log.get().debug("Appending the command call to " + file);
    Files.write(file, Collections.singletonList(unixCommandCall), StandardOpenOption.APPEND);
    log.get().debug("Appended the command call to " + file);
  }
  return this;
}
 
Example 15
Source File: GitDestinationTest.java    From copybara with Apache License 2.0 5 votes vote down vote up
@Test
public void processEmptyCommit() throws Exception {
  fetch = "master";
  push = "master";
  Files.write(workdir.resolve("test.txt"), "some content".getBytes());
  DummyRevision ref = new DummyRevision("origin_ref");
  process(firstCommitWriter(), ref);
  EmptyChangeException thrown =
      assertThrows(EmptyChangeException.class, () -> process(newWriter(), ref));
  assertThat(thrown).hasMessageThat().contains("empty change");
}
 
Example 16
Source File: EciesEncryptionClient.java    From protect with MIT License 4 votes vote down vote up
public void decryptFile() throws BadPaddingException, IllegalBlockSizeException, ClassNotFoundException,
		IOException, ResourceUnavailableException, BelowThresholdException {

	// Print status
	System.out.println("-----------------------------------------------------------");
	System.out.println("Beginning decryption of file: " + this.inputFile);

	// Reading ciphertext
	System.out.print("Reading input file: " + this.inputFile + "... ");
	final byte[] ciphertextData = Files.readAllBytes(inputFile.toPath());
	System.out.println(" (done)");
	System.out.println("Read " + ciphertextData.length + " bytes of ciphertext.");
	System.out.println();

	// Extract public value from ciphertext
	System.out.print("Extracting public value from ciphertext: " + this.inputFile + "... ");
	final EcPoint publicValue = EciesEncryption.getPublicValue(ciphertextData);
	System.out.println(" (done)");
	System.out.println("Public Value is: " + publicValue);
	System.out.println();

	// Get public key and current epoch from the server
	System.out.print("Accessing public key for secret: " + this.secretName + "... ");
	final SimpleEntry<List<EcPoint>, Long> shareVerificationKeysAndEpoch = this.getServerVerificationKeys(secretName);
	System.out.println(" (done)");
	final EcPoint publicKey = shareVerificationKeysAndEpoch.getKey().get(0);
	final long currentEpoch = shareVerificationKeysAndEpoch.getValue();
	System.out.println("Public key for secret:    " + publicKey);
	System.out.println("Current epoch for secret: " + currentEpoch);
	System.out.println();

	// Get public key and current epoch from the server
	System.out.print("Performing threshold exponentiation on public value using: " + this.secretName + "... ");
	final EcPoint exponentiationResult = this.exponentiatePoint(publicValue, currentEpoch);
	System.out.println(" (done)");
	System.out.println("Shared secret obtained:    " + exponentiationResult);
	System.out.println();

	// Perform ECIES decryption
	System.out.print("Performing ECIES decryption of file content... ");
	final byte[] plaintext = EciesEncryption.decrypt(ciphertextData, exponentiationResult);
	System.out.println(" (done)");
	System.out.println("Plaintext length " + plaintext.length + " bytes.");
	System.out.println();

	// Write plaintext to output file
	System.out.print("Writing plaintext to file: " + this.outputFile + "... ");
	Files.write(this.outputFile.toPath(), plaintext);
	System.out.println(" (done)");
	System.out.println("Wrote " + plaintext.length + " bytes.");
	System.out.println();

	System.out.println("Done.");

}
 
Example 17
Source File: StreamTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public void testLines() throws IOException {
    final Charset US_ASCII = Charset.forName("US-ASCII");
    Path tmpfile = Files.createTempFile("blah", "txt");

    try {
        // zero lines
        assertTrue(Files.size(tmpfile) == 0, "File should be empty");
        try (Stream<String> s = Files.lines(tmpfile)) {
            checkLines(s, Collections.emptyList());
        }
        try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
            checkLines(s, Collections.emptyList());
        }

        // one line
        List<String> oneLine = Arrays.asList("hi");
        Files.write(tmpfile, oneLine, US_ASCII);
        try (Stream<String> s = Files.lines(tmpfile)) {
            checkLines(s, oneLine);
        }
        try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
            checkLines(s, oneLine);
        }

        // two lines using platform's line separator
        List<String> twoLines = Arrays.asList("hi", "there");
        Files.write(tmpfile, twoLines, US_ASCII);
        try (Stream<String> s = Files.lines(tmpfile)) {
            checkLines(s, twoLines);
        }
        try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
            checkLines(s, twoLines);
        }

        // MalformedInputException
        byte[] bad = { (byte)0xff, (byte)0xff };
        Files.write(tmpfile, bad);
        try (Stream<String> s = Files.lines(tmpfile)) {
            checkMalformedInputException(s);
        }
        try (Stream<String> s = Files.lines(tmpfile, US_ASCII)) {
            checkMalformedInputException(s);
        }

        // NullPointerException
        checkNullPointerException(() -> Files.lines(null));
        checkNullPointerException(() -> Files.lines(null, US_ASCII));
        checkNullPointerException(() -> Files.lines(tmpfile, null));

    } finally {
        Files.delete(tmpfile);
    }
}
 
Example 18
Source File: ReutersReaderTest.java    From baleen with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void beforeClass() throws IOException {
  tmpDir = Files.createTempDirectory("reuterstest");
  Files.write(tmpDir.resolve("file.sgm"), SGML.getBytes(StandardCharsets.UTF_8));
}
 
Example 19
Source File: VisFusionFile.java    From hmftools with GNU General Public License v3.0 4 votes vote down vote up
public static void write(@NotNull final String filename, @NotNull List<VisFusionFile> dataList) throws IOException
{
    Files.write(new File(filename).toPath(), toLines(dataList));
}
 
Example 20
Source File: LocalStorageFileAction.java    From smart-testing with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a file set in previous steps and stores the given {@code bytes} with the given {@link OpenOption}s in it.
 *
 * @param bytes
 *     An array of bytes to store as a content of the file
 * @param options
 *     {@link OpenOption}s to be used for storing
 *
 * @return A {@link Path} to the stored file
 *
 * @throws IOException
 *     If anything bad happens
 */
public Path create(byte[] bytes, OpenOption... options) throws IOException {
    Files.createDirectories(path.getParent());
    return Files.write(path, bytes, options);
}