Example usage for java.nio.file Files write

List of usage examples for java.nio.file Files write

Introduction

In this page you can find the example usage for java.nio.file Files write.

Prototype

public static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options)
        throws IOException 

Source Link

Document

Write lines of text to a file.

Usage

From source file:net.e2.bw.idreg.db2ldif.Db2Ldif.java

/**
 * Executes the DB-to-LDIF conversion//from www . ja  v a 2 s  . c o m
 */
private void execute() {

    // You may just specify the DB name
    if (!dbDatabase.startsWith("jdbc:mysql")) {
        dbDatabase = "jdbc:mysql://localhost:3306/" + dbDatabase;
    }

    // Instantiate a DB
    TeamworkDB db = new TeamworkDB(dbDatabase, dbUser, dbPassword);

    StringBuilder ldif = new StringBuilder();
    Map<String, String> userNames = new HashMap<>();

    importUsers(db, ldif, userNames);

    importGroups(db, ldif, userNames);

    if (out == null) {
        System.out.println(ldif);
    } else {
        try {
            Files.write(Paths.get(out), ldif.toString().getBytes("UTF-8"), StandardOpenOption.CREATE);
            System.out.println("Wrote LDIF to " + out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.acmutv.ontoqa.tool.io.IOManager.java

/**
 * Appends string on a resource./*from  w w  w.  j  a  v  a 2 s  . co m*/
 * @param resource the resource to write on.
 * @param string the string to write.
 * @throws IOException when resource cannot be written.
 */
public static void appendResource(String resource, String string) throws IOException {
    Path path = FileSystems.getDefault().getPath(resource).toAbsolutePath();
    Files.write(path, string.getBytes(), StandardOpenOption.APPEND);
}

From source file:de.siegmar.securetransfer.component.Cryptor.java

private byte[] initSalt(final Path baseDir) {
    final Path saltFile = baseDir.resolve("salt");
    try {//from  www. j a  v a  2 s  . co m
        if (Files.exists(saltFile)) {
            return Files.readAllBytes(saltFile);
        }

        final byte[] newSalt = newRandom(SALT_SIZE);
        Files.write(saltFile, newSalt, StandardOpenOption.CREATE_NEW);

        LOG.info("Initialized instance salt at {}", saltFile);
        return newSalt;
    } catch (final IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:io.crate.rest.AdminUIHttpIntegrationTest.java

@Before
public void setup() throws ExecutionException, InterruptedException, IOException {
    Iterable<HttpServerTransport> transports = internalCluster().getInstances(HttpServerTransport.class);
    Iterator<HttpServerTransport> httpTransports = transports.iterator();
    address = ((InetSocketTransportAddress) httpTransports.next().boundAddress().publishAddress()).address();
    // place index file
    final Path indexDirectory = internalCluster().getInstance(Environment.class).libFile().resolve("site");
    Files.createDirectories(indexDirectory);
    final Path indexFile = indexDirectory.resolve("index.html");
    Files.write(indexFile, Collections.singletonList("<h1>Crate Admin</h1>"), Charset.forName("UTF-8"));
}

From source file:jp.toastkid.script.Controller.java

/**
 * Save script to file./*from ww w.  j ava  2 s  .co m*/
 */
@FXML
private void saveScript() {
    try {
        if (new File(scriptName.getText()) != null) {
            final File file = new File(
                    "script" + Language.extension(scriptLanguage.getSelectionModel().getSelectedItem()));
            Files.createFile(file.toPath());
            scriptName.setText(file.getAbsolutePath());
        }
        final File file = new File(scriptName.getText());
        Files.write(file.toPath(), scripterInput.getText().getBytes("UTF-8"), StandardOpenOption.WRITE);
    } catch (final IOException e) {
        LOGGER.error("Caught error.", e);
    }
}

From source file:org.fim.tooling.RepositoryTool.java

public void setFileContent(Path file, String content) throws IOException {
    if (Files.exists(file)) {
        Files.delete(file);//from   w w w  .j  ava2s .c o m
    }

    // Creates a big content based on the provided content
    int fileSize = FILE_SIZE + (301_457 * fileCount);
    StringBuilder sb = new StringBuilder(fileSize);
    int index = 0;
    while (sb.length() < fileSize) {
        index++;
        sb.append("b_").append(index).append(": ").append(content).append('\n');
    }

    Files.write(file, sb.toString().getBytes(), CREATE);
}

From source file:com.rptools.io.TableFileParser.java

/**
 * Save new json file if it doesn't exist. Delete the text file.
 *
 * @param file Path to file//from  w  w  w. ja v a 2s  .  c  o  m
 * @param builder RPTable builder to print to JSON file
 * @return Boolean: If the .json file already existed and will be parsed separately
 */
private boolean updateResourceFiles(Path file, RPTable.Builder builder) throws IOException {
    File json = new File(file.toString().replace(EXT_TXT, EXT_JSON));
    Files.delete(file);
    boolean isNew = json.createNewFile();
    Files.write(json.toPath(), Lists.newArrayList(JsonFormat.printer().print(builder)), UTF_8);
    return isNew;
}

From source file:org.apache.flink.client.CliFrontendAddressConfigurationTest.java

/**
 * Test that the CliFrontent is able to pick up the .yarn-properties file from a specified location.
 */// w  w w  . j av a2 s.c o m
@Test
public void testYarnConfig() {
    try {
        File tmpFolder = folder.newFolder();
        String currentUser = System.getProperty("user.name");

        // copy reference flink-conf.yaml to temporary test directory and append custom configuration path.
        File confFile = new File(
                CliFrontendRunTest.class.getResource("/testconfigwithyarn/flink-conf.yaml").getFile());
        File testConfFile = new File(tmpFolder, "flink-conf.yaml");
        org.apache.commons.io.FileUtils.copyFile(confFile, testConfFile);
        String toAppend = "\nyarn.properties-file.location: " + tmpFolder;
        // append to flink-conf.yaml
        Files.write(testConfFile.toPath(), toAppend.getBytes(), StandardOpenOption.APPEND);
        // copy .yarn-properties-<username>
        File propertiesFile = new File(
                CliFrontendRunTest.class.getResource("/testconfigwithyarn/.yarn-properties").getFile());
        File testPropertiesFile = new File(tmpFolder, ".yarn-properties-" + currentUser);
        org.apache.commons.io.FileUtils.copyFile(propertiesFile, testPropertiesFile);

        // start CLI Frontend
        CliFrontend frontend = new CliFrontend(tmpFolder.getAbsolutePath());

        CommandLineOptions options = mock(CommandLineOptions.class);

        frontend.updateConfig(options);
        Configuration config = frontend.getConfiguration();

        checkJobManagerAddress(config, CliFrontendTestUtils.TEST_YARN_JOB_MANAGER_ADDRESS,
                CliFrontendTestUtils.TEST_YARN_JOB_MANAGER_PORT);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:org.fim.command.DetectCorruptionCommandTest.java

private void simulateHardwareCorruption(String fileName) throws IOException {
    Path file = rootDir.resolve(fileName);
    // Keep original timestamps
    BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);

    // A zero byte appears in the middle of the file
    byte[] bytes = Files.readAllBytes(file);
    bytes[bytes.length / 2] = 0;//from   w  w w  . j  a  v  a  2 s  . c o  m

    Files.delete(file);
    Files.write(file, bytes, CREATE);

    // Restore the original timestamps
    Files.getFileAttributeView(file, BasicFileAttributeView.class).setTimes(attributes.lastModifiedTime(),
            attributes.lastAccessTime(), attributes.creationTime());
}