×

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

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

&& Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Java String endsWith() method

Checks whether this String ends with the specified suffix or not. Syntax public boolean endsWith(String Suffix) Parameter Suffix : It takes suffix as a parameter  i.e. Sequence of characters Returns It returns true when the current...

1 minute read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.