tags:

views:

1471

answers:

3

Hi, i want create text file if file allready exists it should not create new file it should append to next 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 allready exist

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

what i have to do?

Thanks for reply suhas

+7  A: 

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.

Kirtan
To be precise, 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.
Stephen C
This is the best way to approach this problem. All other check-then-create methods can fail due to non-atomic file operations. On most systems, the append-create operation is atomic. The FileOutputStream class directly sets up a FileDescriptor in append mode, which is the correct operation.
brianegge
+4  A: 

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);

Stephen C
A: 

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.

Adamski