This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes Writing to a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Writing to a file" Watch "Writing to a file" New topic
Author

Writing to a file

Rahul Sudip Bose
Ranch Hand

Joined: Jan 21, 2011
Posts: 637

I am trying to make a java program to make a simple XML files for my Deployment descriptors in Tomcat, in windows 7.
The problems are :
1.The web.txt file is blank
2.The web.txt file is not renamed to web.xml

I have a doubt, can i make a .xml file and write text to it OR, do i have to make a .txt file - write the text - and then rename it to .xml ?

The code :




SCJP 6. Learning more now.
Vishwanath Krishnamurthi
Ranch Hand

Joined: Jun 04, 2007
Posts: 331
Rahul Sudip Bose wrote:
1.The web.txt file is blank

Try flushing the printWriter:



Rahul Sudip Bose wrote:
I have a doubt, can i make a .xml file and write text to it OR, do i have to make a .txt file - write the text - and then rename it to .xml ?

Yes, You can create an xml file and write to it.

And one more thing, don't forget to close the PrintWriter


Blog
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19674
    
  18

Vishwanath is right. You don't flush() or close() the stream, so it may still cache the data. flush() ensures this cached data is written to the file; close() automatically flushes as well.

As for the renaming not working, that's because you didn't close() the stream. As a result, the JVM still has a lock on the file, and that causes the renaming to fail.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Rahul Sudip Bose
Ranch Hand

Joined: Jan 21, 2011
Posts: 637

Thanks to all for making it work.

Theory for other readers with same doubt : flush and close
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Writing to a file