File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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

Sharada Kumaran
Greenhorn

Joined: May 23, 2001
Posts: 29
I am copying text from a TextArea and writing it into a file, using filewriter/printwriter.
The file ends up having junk characters wherever a new line should be. Why is this? and what is an elegant solution?
I also want to take this opportunity to show my gratitude to all the friendly ranchers who have helped me so much in the past. I hope I can do the same for you guys.


Sharon
Mindy Wu
Ranch Hand

Joined: Jan 12, 2001
Posts: 121
You are in the right track!
I have done it in this way:
File outputFile = new File("FileName.java");
FileOutputStream javaFile = new FileOutputStream(outputFile);
javaFile.write(contentsgoeshere.getBytes());
javaFile.flush();
javaFile.close();
You can also user printwriter:
PrintWriter file = new PrintWriter(new FileWriter(filename, false));
file.println( "Contents from textarea");
file.close();
If you set the boolean to false, it will not overwrite the existing file, but it will append the new lines to the end of the file.
If you set the boolean to true,it will overwrite the file everytime when you run the program.
Hope this helps!
Cheers!
Mindy
[This message has been edited by Mindy Wu (edited July 06, 2001).]
Sharada Kumaran
Greenhorn

Joined: May 23, 2001
Posts: 29
My requirement is that I should be able to write into a file, using App1, and read from the same file using App2. I have used the same procedure that you have , Mindy, but my problem is that if my text has tab spaces ('/t'), then while reading the file, it diplays junk, where it should display tab spaces . At the time I posted the first query, it wasn't reading new line either, but I overcame that using BufferedReader.readLine()
The problem now is with diplaying tab spaces.
Here is what I am doing to read -
Sharada Kumaran
Greenhorn

Joined: May 23, 2001
Posts: 29
The problem was with painting a string with tab characters. It cannot paint tab characters, instead it shows junk. I fixed it by replacing "\t" with " ".
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Writing to a file