Java Path File Name nio writeFile(String pathname, String data)

Here you can find the source of writeFile(String pathname, String data)

Description

Writes a string to the specified file using the default encoding.

License

BSD License

Parameter

Parameter Description
pathname the path to the file.
data the string to write.

Exception

Parameter Description
IOException an exception

Declaration

public static void writeFile(String pathname, String data) throws IOException 

Method Source Code

//package com.java2s;
/* Copyright ? 2015 Gerald Rosenberg.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the License.md file.
 *//*from w  w  w .j  av a  2 s  .c  o m*/

import java.io.File;
import java.io.IOException;

import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;

import java.nio.file.StandardOpenOption;

import java.util.HashSet;

import java.util.Set;

public class Main {
    /**
     * Writes a string to the specified file using the default encoding.
     * 
     * If the file path doesn't exist, it's created. If the file exists, it is overwritten.
     * 
     * @param pathname the path to the file.
     * @param data the string to write.
     * @throws IOException
     */
    public static void writeFile(String pathname, String data) throws IOException {
        write(new File(pathname), data, false);
    }

    public static void write(File file, String data, boolean append) throws IOException {
        Set<OpenOption> options = new HashSet<OpenOption>();
        options.add(StandardOpenOption.CREATE);
        options.add(StandardOpenOption.WRITE);
        if (append) {
            options.add(StandardOpenOption.APPEND);
        } else {
            options.add(StandardOpenOption.TRUNCATE_EXISTING);
        }
        write(file, data, options.toArray(new OpenOption[options.size()]));
    }

    private static void write(File file, String data, OpenOption... options) throws IOException {
        Path path = file.toPath();
        Files.write(path, data.getBytes(), options);
    }
}

Related

  1. unzipFile(String fileName, String targetPath)
  2. uploadFileToServer(InputStream input, String filename, String usercode, String basePath)
  3. validateDockerfilePath(String name)
  4. which(Path path, String name)
  5. writeDataFile(final String resourceName, final Path sourcePath)
  6. writeFileFromInputStream(String the_path, String the_filename, InputStream the_sis)