This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell 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


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: 3602
        
      15
    \ 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: 19697
        
      20

    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
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: File Create Operation