FileOutputStream

Append output to file with FileOutputStream

This is an example of how to append output to a file using the FileOutputStream. The FileOutputStream is an output stream for writing data to a File or to a FileDescriptor. Appending output to a file implies that you should:

  • Create a new File instance by converting the given pathname string into an abstract pathname.
  • Create a new FileOutputStream to write to the file represented by the specified File object.
  • Write bytes from a specified byte array to this file output stream, using write(byte[] b) API method.
  • Don’t forget to close the stream, using its close() API method.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class AppendOutputToFileWithFileOutputStream {
	
	public static void main(String[] args) {
		
		String s = "Java Code Geeks - Java Examples";
		
		File file = new File("outputfile.txt");
		
		FileOutputStream fos = null;

		try {
			
			fos = new FileOutputStream(file, true);
			
			// Writes bytes from the specified byte array to this file output stream 
			fos.write(s.getBytes());

		}
		catch (FileNotFoundException e) {
			System.out.println("File not found" + e);
		}
		catch (IOException ioe) {
			System.out.println("Exception while writing file " + ioe);
		}
		finally {
			// close the streams using close method
			try {
				if (fos != null) {
					fos.close();
				}
			}
			catch (IOException ioe) {
				System.out.println("Error while closing stream: " + ioe);
			}

		}
		
	}

}

 
This was an example of how to append output to a file using the FileOutputStream in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Anoninu
Anoninu
2 years ago

Shouldn’t append add the text to the end of the file instead of creating a new file every time?

Back to top button