3
votes

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?

3
Your question is not clear, but I guess you want to append to a file if it already exists, right?Kirtan
yes, want to append to a file if it already existssuhas

3 Answers

12
votes

You can use the following code to append to a file which already exists -

try {
    BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));
    out.write("data");
    out.close();
} catch (IOException e) { }

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:

...passing true as the 2nd argument causes the file to be created if it doesn't exist and to be opened for appending if it does exist.

10
votes

do i have to check the condition if(file.exists){ }else{ new File(); }

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 returns false, 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 calling new FileOutputStream(file);

1
votes

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 a FileWriter with the append flag set to true; e.g.

PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("foo.txt", true)));
pw.println("Hello, World");
pw.close();

This will create the file if it does not exist or else append to the end of it otherwise.