Java Utililty Methods Write String to File

List of utility methods to do Write String to File

Description

The list of methods to do Write String to File are organized into topic(s).

Method

voidwriteFile(File file, Iterable lines)
Write a bunch of Strings to a file, overwriting anything that was on it
if (file == null)
    throw new IOException("got null file");
if (file.isDirectory())
    throw new IOException(file + " is a directory");
file.createNewFile();
PrintWriter pw = new PrintWriter(file, "UTF8");
try {
    for (String line : lines)
...
voidwriteFile(File file, String content)
write File
FileWriter fw = null;
try {
    fw = new FileWriter(file);
    fw.write(content);
    fw.close();
} catch (IOException e) {
    e.printStackTrace();
} finally {
...
voidwriteFile(File file, String content)
Write content to file
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
out.write(content);
out.close();
voidwriteFile(File file, String content)
write File
if (!file.getParentFile().isDirectory()) {
    file.getParentFile().mkdirs();
BufferedWriter out = null;
try {
    out = new BufferedWriter(new FileWriter(file));
    out.write(content);
} finally {
...
voidwriteFile(File file, String content)
write File
writeFile(file, content, false);
booleanwriteFile(File file, String content)
write File
if (!file.exists()) {
    try {
        file.createNewFile();
    } catch (IOException e) {
        return false;
FileWriter w = null;
...
voidwriteFile(File file, String content)
Write some text into a file (and create it if doesn't exist)
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();
voidwriteFile(File file, String content)
Reads some bytes from the file.
if (!file.exists()) {
    file.getParentFile().mkdirs();
FileWriter out = null;
try {
    out = new FileWriter(file);
    out.write(content);
} finally {
...
booleanwriteFile(File file, String content, String charset)
write File
try {
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
    bw.write(content);
    bw.flush();
    bw.close();
    return true;
} catch (IOException e) {
    return false;
...
voidwriteFile(File file, String content, String charsetName)
write File
File parentFolder = file.getParentFile();
if (!parentFolder.exists()) {
    parentFolder.mkdirs();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charsetName));
try {
    writer.write(content);
} finally {
...