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

The following are Jave code examples for showing how to use write() of the java.nio.file.Files 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: Hobbes-v1   File: FileUtils.java   View Source Code Vote up 8 votes
public static void replaceFileLineStartsWith(String oldLine, String newLine, String filePath) {
  Path path = Paths.get(filePath);
  List<String> fileContent;
  try {
    fileContent = new ArrayList<>(Files.readAllLines(path, StandardCharsets.UTF_8));
    for (int i = 0; i < fileContent.size(); i++) {
      if (fileContent.get(i).startsWith(oldLine)) {
        fileContent.set(i, newLine);
        break;
      }
    }
    Files.write(path, fileContent, StandardCharsets.UTF_8);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
Example 2
Project: openjdk-jdk10   File: BytesAndLines.java   View Source Code Vote up 7 votes
/**
 * Exercise Files.readAllBytes(Path) on custom file system. This is special
 * because readAllBytes was originally implemented to use FileChannel
 * and so may not be supported by custom file system providers.
 */
public void testReadAllBytesOnCustomFS() throws IOException {
    Path myfile = PassThroughFileSystem.create().getPath("myfile");
    try {
        int size = 0;
        while (size <= 1024) {
            byte[] b1 = genBytes(size);
            Files.write(myfile, b1);
            byte[] b2 = Files.readAllBytes(myfile);
            assertTrue(Arrays.equals(b1, b2), "bytes not equal");
            size += 512;
        }
    } finally {
        Files.deleteIfExists(myfile);
    }
}
 
Example 3
Project: instalint   File: InputFileBuilderTest.java   View Source Code Vote up 6 votes
@Test
public void testCreate() throws IOException {
  when(langDetection.language(any(InputFile.class))).thenReturn("java");

  Path path = temp.getRoot().toPath().resolve("file");
  Files.write(path, "test".getBytes(StandardCharsets.ISO_8859_1));
  ClientInputFile file = new TestClientInputFile(path, true, StandardCharsets.ISO_8859_1);

  InputFileBuilder builder = new InputFileBuilder(langDetection, metadata);
  SonarLintInputFile inputFile = builder.create(file);

  assertThat(inputFile.type()).isEqualTo(InputFile.Type.TEST);
  assertThat(inputFile.file()).isEqualTo(path.toFile());
  assertThat(inputFile.language()).isEqualTo("java");
  assertThat(inputFile.lines()).isEqualTo(1);

  assertThat(builder.langDetection()).isEqualTo(langDetection);
}
 
Example 4
Project: jdk8u-jdk   File: FailingConstructors.java   View Source Code Vote up 6 votes
private static void realMain(String[] args) throws Throwable {
    test(false, new File(fileName));

    /* create the file and write its contents */
    File file = File.createTempFile(fileName, null);
    file.deleteOnExit();
    Files.write(file.toPath(), FILE_CONTENTS.getBytes());

    test(true, file);
    file.delete();
}
 
Example 5
Project: tools   File: EncyptionKeyProviderTest.java   View Source Code Vote up 6 votes
@Test()
public void testTrigger() throws Exception {
    final Path keyfile = Paths.get("./junit/etc/minebox/randomkey.txt");
    try {
        Assert.assertFalse(Files.exists(keyfile));
        final LazyEncyptionKeyProvider key = new LazyEncyptionKeyProvider("./junit/etc/minebox/randomkey.txt");
        final ListenableFuture<String> masterPassword = key.getMasterPassword();
        Assert.assertFalse(masterPassword.isDone());
        Files.write(keyfile, PWBYTES);
        Thread.sleep(1000);
        Assert.assertTrue(masterPassword.isDone());
        Assert.assertEquals(PW, key.getImmediatePassword());
    } finally {
        Files.delete(keyfile);
    }
}
 
Example 6
Project: Limitart   File: FileUtil.java   View Source Code Vote up 6 votes
public static void writeNewFile(String path, String fileName, byte[] content) throws IOException {
	File file = new File(path);
	if (!file.exists()) {
		if (!file.mkdirs()) {
			throw new IOException("make dir failed!");
		}
	} else {
		if (!file.isDirectory()) {
			return;
		}
	}
	File temp = new File(path + "//" + fileName);
	if (!temp.exists()) {
		if (!temp.createNewFile()) {
			throw new IOException("create new file failed!");
		}
	}
	Files.write(temp.toPath(), content);
}
 
Example 7
Project: FEFEditor   File: Selection.java   View Source Code Vote up 6 votes
private void openDialogueDLC() {
    FileChooser chooser = new FileChooser();
    File file = chooser.showOpenDialog(GuiData.getInstance().getStage());
    if (file != null) {
        try {
            File workingFile = File.createTempFile("FEFWORKING", null, FileData.getInstance().getTemp());
            FileData.getInstance().setWorkingFile(workingFile);
            byte[] out = Files.readAllBytes(Paths.get(file.getCanonicalPath()));
            Files.write(Paths.get(workingFile.getCanonicalPath()), out);

            FXMLLoader loader = new FXMLLoader(FEFEditor.class.getResource("gui/fxml/fates/DialogueDLC.fxml"));
            content = loader.load();
            changeContent();
            DialogueDLC controller = loader.getController();
            controller.addAccelerators();

            FileData.getInstance().getWorkingFile().deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 8
Project: FlashLib   File: ModeSelectorControl.java   View Source Code Vote up 6 votes
public void saveModes(File file){
	ArrayList<String> lines = new ArrayList<String>();
	
	lines.add("<?xml version=\"1.0\" ?>");
	lines.add("<mode-selector>");
	for (int i = 0; i < modes.size(); i++) {
		lines.add("\t<mode name=\""+modes.get(i).name+"\" value=\""+modes.get(i).value+"\" />");
	}
	lines.add("</mode-selector>");
	
	try {
		Files.write(file.toPath(), lines, StandardOpenOption.CREATE);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 9
Project: FolderSync   File: AuthService.java   View Source Code Vote up 5 votes
public CreateUserResponse createUser(LoginRequest req){
	if(users.containsKey(req.getUserName())){
		req.setPassword("");
		return new CreateUserResponse(Constants.ALREADY_EXISTS,false, req);
	}else{
		users.put(req.getUserName(), req.getPassword());
		try {
			Files.write(Paths.get(Constants.DATA_FILE_PATH), req.getUserName().concat("=").concat(req.getPassword()).getBytes(), StandardOpenOption.APPEND);
		} catch (Exception e) {
			logger.error("Error",e);
		}
		req.setPassword("");
		return new CreateUserResponse(Constants.CREATED, true, req);
	}
}
 
Example 10
Project: jmzTab-m   File: FileSystemStorageService.java   View Source Code Vote up 5 votes
@Override
public UserSessionFile store(String fileContent, String sessionId) {
    String filename = UUID.randomUUID() + ".mztab";
    try {
        Path sessionPath = buildSessionPath(sessionId);
        Files.createDirectories(sessionPath);
        Files.write(buildPathToFile(sessionPath, filename), fileContent.
            getBytes("UTF-8"), StandardOpenOption.CREATE,
            StandardOpenOption.WRITE);
        return new UserSessionFile(filename, sessionId);
    } catch (IOException e) {
        throw new StorageException("Failed to store file " + filename, e);
    }
}
 
Example 11
Project: oscm-app   File: Initializer.java   View Source Code Vote up 5 votes
/**
 * Replace the package names from "com.fujitsu.bss.app" to "org.oscm.app" in
 * the existing log files.
 */
private void replacePackageName(String filePath) {
    try {
        Path path = Paths.get(filePath);
        Charset charset = StandardCharsets.UTF_8;
        String content = new String(Files.readAllBytes(path), charset);
        content = content.replaceAll("com.fujitsu.bss.app", "org.oscm.app");
        Files.write(path, content.getBytes(charset));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 12
Project: Pet-Supply-Store   File: DriveStorage.java   View Source Code Vote up 5 votes
@Override
public boolean saveData(StoreImage data) {
	// We return true so we do not trigger an error. This is intended
	if (!dataIsStorable(data)) {
		return true;
	}
	
	Path imgFile = workingDir.resolve(Long.toString(data.getId()));
	if (imgFile.toFile().exists()) {
		return true;
	}
	
	ReadWriteLock l = getIDLock(data.getId());
	l.writeLock().lock();
	
	try {
		Files.write(imgFile, data.getByteArray(), 
				StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
	} catch (IOException ioException) {
		log.warn("An IOException occured while trying to write the file \"" + imgFile.toAbsolutePath() 
				+ "\" to disk.", ioException);
		return false;
	} finally {
		l.writeLock().unlock();
	}
	
	return true;
}
 
Example 13
Project: 3DSFE-Randomizer   File: AVerifier.java   View Source Code Vote up 5 votes
private static void outputErrorLog(List<File> failures) {
    List<String> out = new ArrayList<>();
    out.add("The following files failed to verify: ");
    for(File f : failures)
        out.add(f.getAbsolutePath());
    try {
        Files.write(Paths.get(System.getProperty("user.dir") + "/VerificationFailures.txt"), out);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 14
Project: smart-testing   File: ChangedTestsDetectorTest.java   View Source Code Vote up 5 votes
@Test
public void should_not_find_untracked_tests_as_changed() throws IOException {
    //given
    Configuration configuration = createConfiguration("7699c2c", "04d04fe");
    final File testFile = gitFolder.newFile("core.src.test.java.org.arquillian.smart.testing.CalculatorTest.java");
    Files.write(testFile.toPath(), ("package org.arquillian.smart.testing;\n"
        + "\n"
        + "import org.junit.Assert;\n"
        + "import org.junit.Test;\n"
        + "\n"
        + "public class CalculatorTest {\n"
        + "\n"
        + "    @Test\n"
        + "    public void should_add_numbers() {\n"
        + "        Assert.assertEquals(6, 4 + 2);\n"
        + "    }\n"
        + "}").getBytes(), StandardOpenOption.APPEND);

    final ChangedTestsDetector changedTestsDetector =
        new ChangedTestsDetector(new GitChangeResolver(), new NoopStorage(), gitFolder.getRoot(),
            className -> className.endsWith("Test"), configuration);

    // when
    final Collection<TestSelection> changedTest = changedTestsDetector.getTests();

    // then
    assertThat(changedTest).extracting(TestSelection::getClassName)
        .containsOnly("org.arquillian.smart.testing.vcs.git.NewFilesDetectorTest")
        .doesNotContain("org.arquillian.smart.testing.CalculatorTest");
}
 
Example 15
Project: keycloak-monitoring-prometheus   File: MonitoringEventListenerProvider.java   View Source Code Vote up 5 votes
private File getOrCreateCounterFile(String fileName) {
    File f = new File(eventsDirectory + File.separator + fileName);
    if (!f.exists()) {
        try {
            logger.debug("File for name: " + fileName + "does not exist, creating");
            f.createNewFile();
            Files.write(f.toPath(), "0".getBytes(Charset.forName("UTF-8")));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return f;
}
 
Example 16
Project: openjdk-jdk10   File: VMProps.java   View Source Code Vote up 5 votes
/**
 * Dumps the map to the file if the file name is given as the property.
 * This functionality could be helpful to know context in the real
 * execution.
 *
 * @param map
 */
protected static void dump(Map<String, String> map) {
    String dumpFileName = System.getProperty("vmprops.dump");
    if (dumpFileName == null) {
        return;
    }
    List<String> lines = new ArrayList<>();
    map.forEach((k, v) -> lines.add(k + ":" + v));
    try {
        Files.write(Paths.get(dumpFileName), lines, StandardOpenOption.APPEND);
    } catch (IOException e) {
        throw new RuntimeException("Failed to dump properties into '"
                + dumpFileName + "'", e);
    }
}
 
Example 17
Project: manifold   File: Hyde.java   View Source Code Vote up 4 votes
private static void writeTo(File f, String html) throws IOException {
  Files.write(Paths.get(f.getPath()), html.getBytes(StandardCharsets.UTF_8));
}
 
Example 18
Project: devtools-driver   File: ExampleMobileSafariWebTest.java   View Source Code Vote up 4 votes
private static void takeScreenshot() throws Exception {
  byte[] screenshotBytes = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
  Path screenshotPath = Files.createTempFile("screenshot", ".png");
  Files.write(screenshotPath, screenshotBytes);
  logger.atInfo().log("Screenshot written to: %s", screenshotPath);
}
 
Example 19
Project: Cosmo   File: Utility.java   View Source Code Vote up 3 votes
/**
 * Funzione utilizzata per creare il file .java
 * 
 * @param nomeClasse nome del file da dover creare
 * @param source stringa contenente il codice sorgente
 * @param path percorso di creazioen
 * @throws Exception 
 */
public static void creaFileJava(String nomeClasse, String source, String path) throws Exception
{
    File root = new File(path);
    File sourceFile = new File(root, "/"+nomeClasse+".java");
    sourceFile.getParentFile().mkdirs();
    Files.write(sourceFile.toPath(), source.getBytes(StandardCharsets.UTF_8));
}
 
Example 20
Project: fxutils   File: FXDialog.java   View Source Code Vote up 2 votes
/**
 * Shows a file system dialog and saves a file to the selected path.
 * @param bytes The byte content of the file
 * @param owner The Stage object that will own the dialog
 * @param extensions The extensions allowed for the file. Do not prepend '.' to the extension
 * @throws IOException - if it fails to write the file
 */
public static void saveFile(byte[] bytes, Stage owner, String... extensions) throws IOException {
	File dest = createFileChooser("Save file", extensions).showSaveDialog(owner);
	Files.write(Paths.get(dest.toURI()), bytes);
}