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

FilewriteFile(File f, String body)
Create a new data file with specified initial contents.
f.getParentFile().mkdirs();
OutputStream os = new FileOutputStream(f);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
pw.print(body);
pw.flush();
os.close();
return f;
FilewriteFile(File f, String content)
write File
FileOutputStream fsout = new FileOutputStream(f);
fsout.write(content.toString().getBytes());
fsout.close();
return f;
voidwriteFile(File f, String content)
write File
BufferedWriter writer = null;
try {
    writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "utf-8"));
    writer.write(content);
} catch (Exception e) {
    throw e;
} finally {
    if (writer != null) {
...
voidwriteFile(File f, String content, String encoding)
write File
OutputStreamWriter out = null;
try {
    if (f.getName().endsWith(".gz"))
        out = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(f, false)), encoding);
    else
        out = new OutputStreamWriter(new FileOutputStream(f, false), encoding);
    out.append(content);
} finally {
...
voidwriteFile(File f, String contents)
Write the given contents with UTF-8 encoding to the given file.
Writer out = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
try {
    out.write(contents);
} finally {
    out.close();
voidwriteFile(File f, String entry)
This method appends a single string to a text file.
try {
    final BufferedWriter out = new BufferedWriter(new FileWriter(f, true));
    out.write(entry);
    out.close();
} catch (IOException e) {
    System.err.println("Problem writing to the file");
booleanwriteFile(File f, String s)
write File
BufferedWriter out = getWriter(f);
if (out != null) {
    try {
        out.write(s);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
...
voidwriteFile(File f, String str)
write File
FileOutputStream fos = new FileOutputStream(f);
try {
    fos.write(str.getBytes("UTF-8"));
    fos.flush();
} finally {
    fos.close();
voidwriteFile(File f, String str)
Writes a string(str) to a File(f) ** THis method overwrites any data in the file
if (!f.exists()) {
    if (!f.createNewFile()) {
        throw new Exception("File was not created!");
if (!f.canWrite())
    throw new Exception("No permission to write file!");
else {
...
voidwriteFile(File f, String text)
write File
FileWriter fileWriter = null;
BufferedWriter bufferedWriter = null;
try {
    fileWriter = new FileWriter(f);
    bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write(text);
} finally {
    if (bufferedWriter != null)
...