Java Text File Write nio writeToFile(File file, String content)

Here you can find the source of writeToFile(File file, String content)

Description

Writes given string to a file.

License

Open Source License

Declaration

public static void writeToFile(File file, String content) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class Main {
    private static final String CHARSET = "UTF-8";

    /**//from   w  ww  .  j a  v  a2  s.  co  m
     * Writes given string to a file.
     * Will create the file if it does not exist yet.
     */
    public static void writeToFile(File file, String content) throws IOException {
        createFile(file);
        Files.write(file.toPath(), content.getBytes(CHARSET));
    }

    /**
     * Creates a file if it does not exist along with its missing parent directories
     *
     * @return true if file is created, false if file already exists
     */
    public static boolean createFile(File file) throws IOException {
        if (file.exists()) {
            return false;
        }

        createParentDirsOfFile(file);

        return file.createNewFile();
    }

    /**
     * Creates parent directories of file if it has a parent directory
     */
    public static void createParentDirsOfFile(File file) throws IOException {
        File parentDir = file.getParentFile();

        if (parentDir != null) {
            createDirs(parentDir);
        }
    }

    /**
     * Creates the given directory along with its parent directories
     *
     * @param dir the directory to be created; assumed not null
     * @throws IOException if the directory or a parent directory cannot be created
     */
    public static void createDirs(File dir) throws IOException {
        if (!dir.exists() && !dir.mkdirs()) {
            throw new IOException("Failed to make directories of " + dir.getName());
        }
    }
}

Related

  1. writeStringToFile(final File file, final String content)
  2. writeStringToFile(String s, File f)
  3. writeTextFile(final File file, final String text)
  4. writeTextFile(String file, String articleContent)
  5. writeTo(File file, String content)
  6. writeToFile(File file, String str)
  7. writeToFile(final File file, final String data)
  8. writeToFile(String content, String fileName)
  9. writeToFile(String content, String fileName, boolean createFile)