Java File Append LIne appendLineToTextFile(File file, String line)

Here you can find the source of appendLineToTextFile(File file, String line)

Description

Appends a new line to a text file.

License

Open Source License

Parameter

Parameter Description
file a parameter
line a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static void appendLineToTextFile(File file, String line) throws IOException 

Method Source Code


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

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

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

public class Main {
    /**/*from w w  w .j a v a2 s. co m*/
     * Appends a new line to a text file. If file doesn't exists it is created.
     * 
     * @param file
     * @param line
     * @throws IOException
     */
    public static void appendLineToTextFile(File file, String line) throws IOException {
        boolean newLine = true;

        if (!file.exists()) {
            file.createNewFile();
            newLine = false;
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
        BufferedWriter bw = new BufferedWriter(fw);
        if (newLine) {
            bw.newLine();
        }
        bw.write(line);
        bw.close();
    }
}

Related

  1. appendLines(File file, String[] lines)
  2. appendLinesToFile(Iterable lines, File outFile)
  3. appendLineToFile(String fileName, String format, Object... vals)
  4. AppendLineToFile(String filePath, String text)
  5. appendLineToFile(String path, String line)