Saving a string to a file

J

jay

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_DIRECTORIES);
int returnVal = fc.showSaveDialog(frame);
try
{
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
SF = (file.toString() + ".txt");
FileOutputStream fStream = new
FileOutputStream(SF);
ObjectOutputStream stream = new
ObjectOutputStream(fStream);
stream.writeObject(s);
//stream.writeBytes(s);
stream.flush();
stream.close();
fStream.close();
}
}catch (Exception e) {
JOptionPane op = new JOptionPane();
op.showMessageDialog(null,"A document writing error has
occured");
}
-----------------------------------------------------------------------
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.
 
R

Roedy Green

FileOutputStream fStream = new
FileOutputStream(SF);
ObjectOutputStream stream = new
ObjectOutputStream(fStream);
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
http://mindprod.com/applets/fileio.html
for sample code.
 
V

Venky

May be you can do this way:

File file = fc.getSelectedFile();
FileOutputStream fStream = new FileOutputStream(file);
fstream.write(s.getBytes());
fstream.close();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,990
Messages
2,570,211
Members
46,796
Latest member
SteveBreed

Latest Threads

Top