Velocity Reviews

Velocity Reviews (
-   Java (
-   -   Saving a string to a file (

jay 01-30-2006 03:07 AM

Saving a string to a file
Hi all,
I am trying to save a string that I get from a JTextArea like this:

String s = textArea.getText();

After getting the text I save it using the following code

---------------Simplified to reduce number of lines----------
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIR ECTORIES);
int returnVal = fc.showSaveDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
SF = (file.toString() + ".txt");
FileOutputStream fStream = new
ObjectOutputStream stream = new
}catch (Exception e) {
JOptionPane op = new JOptionPane();
op.showMessageDialog(null,"A document writing error has
This will save everything correctly but it adds some additional
characters in front of the file.
That is if the string 's' contains: this is a test file
After saving it the file itself has some unreadable characters in front
of the actual text.

Does anyone have any ideas of why these characters are being added to
the string once I save it to a file I have tried both
stream.writeObject(s) and stream.writeBytes(s) but they both add the
extra characters.

I know that the string 's' doesn't contain the extra characters because
I print it just before saving and it prints as expected.

Roedy Green 01-30-2006 04:15 AM

Re: Saving a string to a file
On 29 Jan 2006 19:07:25 -0800, "jay" <> wrote,
quoted or indirectly quoted someone who said :

>FileOutputStream fStream = new
> ObjectOutputStream stream = new
> stream.writeObject(s);
> //stream.writeBytes(s);
> stream.flush();
> stream.close();
> fStream.close();

this is using a flame thrower to kill a fly. You could do that more
easily with a DataOutputStream if you don't intend anyone to read it
or a FileWriter if you do. See
for sample code.
Canadian Mind Products, Roedy Green. Java custom programming, consulting and coaching.

Venky 01-30-2006 04:57 AM

Re: Saving a string to a file
May be you can do this way:

File file = fc.getSelectedFile();
FileOutputStream fStream = new FileOutputStream(file);

jay 01-30-2006 05:40 AM

Re: Saving a string to a file
Thanks for your replies, they were definitively a big help.

All times are GMT. The time now is 04:14 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.