×

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data inserted.

However, there are some situations where appending data (a message) to the next line of the file is necessary, such as when logging exceptions together into the file without using logger frameworks.

Files classes of a java. nio package can be used to accomplish this. This class offers a write() function that accepts

  • A file is represented by a Path class object.
  • a byte array containing the file's data

One of the members of the StandardOpenOption enumeration, which has 10 options, namely, create, create new, append, delete, on close, read, sync, spare, truncate existing, and write, dsynccan be sent as a value to an OpenOption (interface) type variable.

The file location, byte array holding the data to be appended, and the option StandardOpenOption.APPEND must be passed when calling this method.

Example

In the Java application below, we are allowing the user to select two components from the array (based on their indices) and execute division between them. The array contains five integer values. ArithmeticException, InputMismatchException, and ArrayIndexOutOfBoundsException are caught by three catch blocks that are placed around this code in a try block. We are calling the writeToFile() method in each one of them.

The write() function of the Files class is used in this method to attach an exception object to a file.

public class LoggingToFile
{
   private static void writeToFile(Exception e) throws IOException
{
      Path logFile = Paths.get("ExceptionLog.txt");
      byte bytes[] = ("\r"+LocalDateTime.now()+": "+e.toString()).getBytes();
Files.write(logFile, bytes, StandardOpenOption.APPEND);
System.out.println("Exception was recorded in your file.");
   }
   public static void main(String [] args) throws IOException {
      Scanner sc = new Scanner(System.in);
int[] arr = {1, 12, 20, 30, 1, 0};
System.out.println("Array: "+Arrays.toString(arr));
System.out.println("Choose the numerator as well as the denominator (not 0) from the above-mentioned array (enter locations 0 to 5)");
      try {
         int x = sc.nextInt();
         int y = sc.nextInt();
         int result = (arr[x])/(arr[y]);
System.out.println("Result of "+arr[x]+"/"+arr[y]+": "+result);
}catch(ArrayIndexOutOfBoundsException ex) {
System.out.println("Warning: You've selected a location that isn't part of the array.");
writeLogToFile(ex);
}catch(ArithmeticException ex) {
System.out.println("Warning: You cannot divide an number with 0");
writeLogToFile(ex);
}catch(InputMismatchException ex) {
System.out.println("Warning: You have entered invalid input");
writeLogToFile(ex);
      }
   }
}

Append to File in Java

Using the classes shown below, we can append to files in Java.

  • Java file append employing FileWriter
  • Java uses BufferedWriter to append material to an existing file.
  • Java program to add text to a file using PrintWriter.
  • Using FileOutputStream, appenda new line to a file in Java.

Java File Append Employing FileWriter

Using the write() function of the Files class, we may create a new file. Internally, the write() function writes a byte array further into a file using an OutputStream.

Use StandardOpenOption to add content to a file that already exists.While creating the material, use APPEND.

File file = new File("append.text");
FileWriter f = new FileWriter(file, true);
f.write("data");
f.close();

Java uses BufferedWriter to Append Material to an Existing File.

To reduce IO operations and boost efficiency, BufferedWriter buffers all data in an inner byte array before writing to the file.

Launch the writer using append mode and enter the true value for the second argument to attach a string to an existing file.

File file = new File("append.text");
FileWriter f = new FileWriter(file, true);
BufferWriter b = new BufferWriter(f);
b.write("data");
b.close();
f.close();

Using PrintWriter, Append Text to a File in Java.

The PrintWriter can be used to write formatting to a file. Because PrintWriter implements every print() method in PrintStream, we can use any format that System.out.println() commands support.

Launch the writer using append mode by giving the second option as true to add material to an existing file.

File file = new File("append.text");
FileWriter f = new FileWriter(file, true);
BufferWriter b = new BufferWriter(f);
PrintWriter p = new PrintWriter(b);
p.println("data");
p.close();
b.close();
f.close();

Using FileOutputStream, Append a New Line to a File in Java.

To write binary data into a file, use FileOutputStream. FileOutputStream is designed for outputting streams of uncompressed bytes, such as image data. Think about using FileWriter to write streams of characters.

Create FileOutputStream in append fashion by giving the second option as true to append material to an existing file.

OutputStreamos = new FileOutputStream(new File("append.txt"), true);
os.write("data".getBytes(), 0, "data".length());
os.close();

Related Topics

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

How to stop execution after a certain time in Java

We will learn how to stop a long-running execution after a set amount of time in this post. We will take a look at a few alternative approaches to this...

6 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Java Lock

A lock is indeed a threaded synchronization technique similar to Java's synchronized blocks, however, locking can be more complex. It's not like we can completely get rid of the synchronized...

5 minutes read.

Java Integer parseUnsignedInt() method

The parseUnsignedInt() method of Java Integer class parses the string argument as an unsigned decimal integer. The second parameter parses the string argument as an unsigned integer in the radix specified...

2 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.