Java Text File Write writeStringToFile(String path, String content)

Here you can find the source of writeStringToFile(String path, String content)

Description

Write the given string content into a file with the specified path.

License

Open Source License

Parameter

Parameter Description
path Path of the file to be written.
content Content of the file.

Exception

Parameter Description
FileNotFoundException an exception
IOException an exception
IllegalArgumentException an exception

Declaration

public static void writeStringToFile(String path, String content) throws IOException, IllegalArgumentException 

Method Source Code


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

import java.io.*;

public class Main {
    /**/*from  www.  j a v  a  2 s. c om*/
     * Write the given string content into a file with the specified path.
     *
     * @param path    Path of the file to be written.
     * @param content Content of the file.
     * @throws FileNotFoundException
     * @throws IOException
     * @throws IllegalArgumentException
     */
    public static void writeStringToFile(String path, String content) throws IOException, IllegalArgumentException {
        writeStringToFile(new File(path), content);
    }

    /**
     * Write the given string content into the given {@link File}.
     *
     * @param file    File to write.
     * @param content Content of the file.
     * @throws FileNotFoundException
     * @throws IOException
     * @throws IllegalArgumentException
     */
    public static void writeStringToFile(File file, String content) throws IOException, IllegalArgumentException {
        if (file == null) {
            throw new IllegalArgumentException("File should not be null.");
        }

        if (!file.exists()) {
            throw new FileNotFoundException("File does not exist: " + file);
        }

        if (!file.isFile()) {
            throw new IllegalArgumentException("Should not be a directory: " + file);
        }

        if (!file.canWrite()) {
            throw new IllegalArgumentException("File cannot be written: " + file);
        }

        try (Writer output = new BufferedWriter(new FileWriter(file))) {
            //FileWriter always assumes default encoding is OK!
            output.write(content);
        }
    }
}

Related

  1. writeStringToFile(String jsonStr, File file)
  2. writeStringToFile(String macroContent, File file)
  3. writeStringToFile(String modifiedLine, String filePath)
  4. writeStringToFile(String path, String content)
  5. writeStringToFile(String path, String content)
  6. writeStringToFile(String path, String contents)
  7. writeStringToFile(String s, File f)
  8. writeStringToFile(String s, File f)
  9. writeStringToFile(String s, File f)