This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "File Create Operation" Watch "File Create Operation" New topic

File Create Operation

Hari Dhanakoti
Ranch Hand

Joined: Jan 07, 2008
Posts: 74

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


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?

Nitesh Kant

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

    Joined: Aug 05, 2005
    Posts: 3432
    \ 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");

    Rob Spoor

    Joined: Oct 27, 2005
    Posts: 19656


    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
    I agree. Here's the link:
    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