Java File Append Text appendToFile(String filename, String str)

Here you can find the source of appendToFile(String filename, String str)

Description

append To File

License

Apache License

Declaration

public static void appendToFile(String filename, String str) 

Method Source Code


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

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

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

public class Main {
    public static void appendToFile(String filename, String str) {
        File f = new File(filename);
        String in = "";
        if (f.exists())
            in = read(filename) + str + "\n";
        else//  ww w .  j  a v a  2 s  . co m
            in = str + "\n";

        write(filename, in);
    }

    public static String read(String filename) {
        File f = new File(filename);

        if (!f.exists()) {

            try {
                f.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        try {
            BufferedReader br = new BufferedReader(new FileReader(filename));

            String line;
            String res = "";
            while ((line = br.readLine()) != null) {
                res += line;
            }

            br.close();

            return res;
        } catch (IOException localIOException) {
            localIOException.printStackTrace();
        }

        return null;
    }

    public static void write(String filename, String data) {
        try {
            File f = new File(filename);

            if (f.exists()) {
                f.delete();
                f.createNewFile();
            }

            FileWriter fw = new FileWriter(filename);
            BufferedWriter bw = new BufferedWriter(fw);

            bw.write(data);

            bw.close();

        } catch (IOException localIOException) {
            localIOException.printStackTrace();
        }
    }
}

Related

  1. appendToFile(String content, String filename)
  2. appendToFile(String contents, String filename)
  3. appendToFile(String file, String line)
  4. appendToFile(String fileName, String content)
  5. appendToFile(String filename, String content, int line)
  6. appendToFile(String filename, String text)
  7. appendToFile(String fileName, String text)
  8. appendToFile(String filename, String text)
  9. appendToFile(String filePath, String content)