Java Write String to File writeFile(File file, String content)

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

Description

Write some text into a file (and create it if doesn't exist)

License

Open Source License

Parameter

Parameter Description
file File where the text will be written
content Text to be written

Exception

Parameter Description
FileNotFoundException If the file cannot be created or is a directory
IOException If an I/O error happend while writing

Declaration

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

Method Source Code

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

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;

import java.io.FileWriter;
import java.io.IOException;

public class Main {
    /**/*from  w  ww .j ava  2 s.  c  o m*/
     * Write some text into a file (and create it if doesn't exist)
     * @param file File where the text will be written
     * @param content Text to be written
     * @throws FileNotFoundException If the file cannot be created or is a directory
     * @throws IOException If an I/O error happend while writing
     */
    public static void writeFile(File file, String content) throws FileNotFoundException, IOException {
        BufferedWriter bw = null;
        boolean created = true;
        try {
            if (!file.exists())
                created = file.createNewFile();
            if (!created) {
                throw new IOException("File cannot be created");
            }
            bw = new BufferedWriter(new FileWriter(file, false));
            bw.write(content);
            bw.flush();
        } catch (FileNotFoundException e) {
            if (bw != null)
                bw.close();
            throw e;
        } finally {
            if (bw != null)
                bw.close();
        }
    }
}

Related

  1. writeFile(File f, String text)
  2. writeFile(File file, Iterable lines)
  3. writeFile(File file, String content)
  4. writeFile(File file, String content)
  5. writeFile(File file, String content)
  6. writeFile(File file, String content)
  7. writeFile(File file, String content)
  8. writeFile(File file, String content)
  9. writeFile(File file, String content, String charset)