File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

File Create Operation

 
Hari Dhanakoti
Ranch Hand
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
     
    Joanne Neal
    Rancher
    Pie
    Posts: 3742
    16
    • 0
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    \ 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
    Sheriff
    Pie
    Posts: 20368
    43
    Chrome Eclipse IDE Java Windows
    • 0
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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"
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic