Java FileWriter Write saveTextFile(File file, String text)

Here you can find the source of saveTextFile(File file, String text)

Description

Change the contents of text file in its entirety, overwriting any existing text.

License

Open Source License

Parameter

Parameter Description
file is a file which can be written to.

Exception

Parameter Description
IllegalArgumentException if param does not comply.
FileNotFoundException if the file does not exist.
IOException if problem encountered during write.

Declaration

public static void saveTextFile(File file, String text) 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;
import java.io.Writer;

public class Main {
    /**//  ww  w.  j a v a  2  s  . c  o m
     * Change the contents of text file in its entirety, overwriting any
     * existing text.
     * 
     * @param file is a file which can be written to.
     * @throws IllegalArgumentException if param does not comply.
     * @throws FileNotFoundException if the file does not exist.
     * @throws IOException if problem encountered during write.
     */
    public static void saveTextFile(File file, String text) throws FileNotFoundException, IOException {
        if (file == null) {
            throw new IllegalArgumentException("File should not be null.");
        }
        if (file.exists() && file.isDirectory()) {
            throw new IllegalArgumentException("Should not be a directory: " + file);
        }
        if (file.exists() && !file.canWrite()) {
        }

        //use buffering
        Writer output = new BufferedWriter(new FileWriter(file));
        try {
            //FileWriter always assumes default encoding is OK!
            output.write(text);
        } finally {
            output.close();
        }
    }
}

Related

  1. saveStringToFile(String fileToSave, String data)
  2. saveStringToFile(String string, String fileName)
  3. saveStringToFile(String text, File fname)
  4. saveTemporaryTermFile(File tempLocation, String word, Collection termList)
  5. saveText(java.io.File f, String text)
  6. saveTextFile(String content, File file, boolean append)
  7. saveTextFile(String contents, File file)
  8. saveTextFile(String fileName, String text)
  9. saveToCache(String md, String in, String res)