Write Or Append To A File Using Java

Introduction

In this short example code I will show you how to create a new file for writing into it or if the file already exists then append to it instead of creating a new file using Java programming language.

If you have a requirement that either you need to log some data into an existing file or create a new file if the file does not exist. Probably when you need to log some statistics data into a file then you need to handle such scenario.

Prerequisites

Java 1.8+ (11 – 12), Maven 3.8.5

Write or Append to File

Now I will write a program to write or append to the file. So, if file does not exist with same name then a file will be created for writing, and if a file exists then new data will be appended to the existing content of the file.

package com.roytuts.java.write.append.data.file;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileApp {

	public static void main(String[] args) throws IOException {
		writeAppendToFile(null);
	}

	public static void writeAppendToFile(final String fileName) throws IOException {
		String outFileName = null;
		if (fileName == null || fileName.trim().length() <= 0) {
			final Date date = new Date();
			final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
			outFileName = sdf.format(date) + ".txt";
		} else {
			outFileName = fileName;
		}

		PrintWriter pw = null;
		final File file = new File(outFileName);

		if (file.exists() && !file.isDirectory()) {
			pw = new PrintWriter(new FileWriter(file, true));

			pw.printf("This is an existing file");
			pw.println();
		} else {
			pw = new PrintWriter(new FileWriter(file));

			pw.printf("This is a new file");
			pw.println();
		}

		pw.close();
	}

}

Testing Write or Append

When you run the above main class, then first time when a file does not exist will be created with the current date and the file is of text type.

So, for the first time you will see the content This is a new file in the file. If the file exists then a string This is an existing file will e appended to the existing content.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *