I want create text file but if the file already exists it should not create new file but should append the text to the content (at the end) of the existing file. How can I do it in Java?
for every one second I'm reading data from inputstream when i stop reading and again i start reading data at that time i should write to same file if file already exist
does I have to check the condition:
if(file.exists){
} else{
new File();
}
What I have to do?
You can use the following code to append to a file which already exists -
If the second argument in FileWriter's constructor is
true
, then bytes will be written to the end of the file rather than the beginning.Quoting Stephen's comment:
No you don't have to do that: see other answers for the solution.
Actually, it would be a bad idea to do something like that, as it creates a potential race condition that might make your application occasionally die ... or clobber a file!
Suppose that the operating system preempted your application immediately after the
file.exists()
call returnsfalse
, and gave control to some other application. Then suppose that the other application created the file. Now when your application is resumed by the operating system it will not realise that the file has been created, and try to create it itself. Depending on the circumstance, this might clobber the existing file, or it might cause this application to throw an IOException due to a file locking conflict.Incidentally,
new File()
does not actually cause any file system objects to be created. That only happens when you 'open' the file; e.g. by callingnew FileOutputStream(file);
If you wish to append to the file if it already exists there's no need to check for its existence at all using
exists()
. You merely need to create aFileWriter
with the append flag set to true; e.g.This will create the file if it does not exist or else append to the end of it otherwise.