Two Laptop Bag*
The moose likes Beginning Java and the fly likes File Create Operation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "File Create Operation" Watch "File Create Operation" New topic
Author

File Create Operation

Hari Dhanakoti
Ranch Hand

Joined: Jan 07, 2008
Posts: 74
Hi,

I am now trying to create a new file for eg: (d:\test\testFile.txt).

If there is no file in such directory how can i create then. If i tend to open the file again then the existing contents of the file needs to be removed and the new content should be the content later.

I made use of the
File file = new File("d:\test\testFile.txt");
file.exists()

and

BufferedWriter out = new BufferedWriter(new FileWriter("d:\test\testFile.txt"));

How could i get make the file created, if the file does not exists and fill up the new contents to the file erasing up the previous contents?


Regards,
Hari
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

Before writing on the file (using BufferedWriter as you have shown in your post), you have to do the following:

  • Check if the file exists. (Using file.exists() method)
  • If it exists, delete the file (Using file.delete() method)


  • After this you can keep writing to the file.
    Make sure you call flush() on the writer after you are done (Close() internally will call flush(), so if you do not need the writer you can close it). This will force the contents on to the file system.

    P.S.: You do not need to create a new file before writing on it. A write will implicitly create the file if it is not present.


    apigee, a better way to API!
    Joanne Neal
    Rancher

    Joined: Aug 05, 2005
    Posts: 3419
        
      12
    \ is a special character in Java Strings so you need to escape it
    File file = new File("d:\test\testFile.txt");
    should be
    File file = new File("d:\\test\\testFile.txt");


    Joanne
    Rob Spoor
    Sheriff

    Joined: Oct 27, 2005
    Posts: 19649
        
      18

    Correct.

    Usually you would get a warning about an invalid character being escaped, but as it happens \t is a tab. Therefore, your file was actually "d:<TAB>est<TAB>estFile.txt"


    SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
    How To Ask Questions How To Answer Questions
     
    Consider Paul's rocket mass heater.
     
    subject: File Create Operation
     
    Similar Threads
    how to save the file in clint side in temp folder
    Creating Directories with FileWriter
    File writer issue
    add text to file
    how to write output of jsp to another file