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

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

Description

Writes content to file, in UTF-8 encoding.

License

Apache License

Parameter

Parameter Description
filename file to create or overwrite.
content content to write.

Return

file reference to file.

Declaration

public static File writeFile(String filename, String content) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;

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

    /**/*w ww . j a v  a2 s.co m*/
     * Writes content to file, in UTF-8 encoding.
     *
     * @param filename file to create or overwrite.
     * @param content content to write.
     * @return file reference to file.
     */
    public static File writeFile(String filename, String content) {
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(filename, FILE_ENCODING);
            pw.write(content);
            pw.flush();
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException("Unable to write to: " + filename, e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
        return new File(filename);
    }
}

Related

  1. writeFile(String destination, byte[] data, boolean append)
  2. writeFile(String filename, Object object)
  3. writeFile(String filename, String content)
  4. writeFile(String fileName, String content)
  5. WriteFile(String filename, String content)
  6. writeFile(String filename, String content)
  7. writeFile(String filename, String content)
  8. writeFile(String fileName, String content)
  9. writeFile(String filename, String content)