How to write file in Java
Last Updated on Friday, 22 February 2013 09:12
In this lessons we will learn how to write content to files with a simple java example demonstrating the usage of BufferedWriter and FileWriter class.
If the file does not already exist, it is automatically created.
Writing file advice
- For an efficient writing it is recommended to use buffering. If you don't provide a buffer size in the BufferedWriter class constructor the default size is 8K (8192 Chars). Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient. If you use unbuffered I/O each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.
- You should always pay attention to IOException and sometimes FileNotFoundException
- BufferedWriter represent resources which you must always clean up explicitly, by calling the close method. When a close method is called on a BufferedWriter, it automatically performs a flush. There is no need to explicitly call flush before calling close.
Flushing the buffered writer
It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer.To flush the stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered.
An IOException signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.
A FileNotFoundException signals that an attempt to open the file denoted by a specified pathname has failed. This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist.
It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.
To append data into an existing file you need to add a second argument in the FileWriter class constructor then bytes will be written to the end of the file rather than the beginning.
Java IO file related subjects
If you have any remark or questions feel free to put a comment.If you enjoyed this tutorial and want to promote it don't hesitate to click on
Tags: java, class, file, write, ioexception, flush