how write value to file?

G

Geoff Cox

Hello,

I'm not clear how to write a vlaue to a file on the hard disk ... I
have the code below and wish to write the getValue() number to disk.

I am guessing that I need to call (with this value) a method to do
this but my following effort is wrong. Please see also the rest of the
code after my signature

writeToFile(scale.getValue());

}

public static String writeToFile (int num)
{
try
{
FileWriter file = new FileWriter("data.txt");
BufferedWriter buffer = new BufferedWriter(file);
buffer.write(num);
buffer.close();
}
catch(IOException e) { System.out.println(e); }
}

Help! please

Geoff

--------------------

public void stateChanged(ChangeEvent event)
{
JSlider src = (JSlider) event.getSource();
if(!src.getValueIsAdjusting())
position.setText("Position is
"+scale.getValue());

writeToFile(scale.getValue());

}

public static String writeToFile (int num)
{
try
{
FileWriter file = new FileWriter("data.txt");
BufferedWriter buffer = new BufferedWriter(file);
buffer.write(num);
buffer.close();
}
catch(IOException e) { System.out.println(e); }
}
 
S

Sharp Tool

I use PrintWriter class:

PrintWriter pw = new PrintWriter(new FileWriter("data.txt"));
pw.println(num);
pw.close();

Cheers
Sharp
 
G

Geoff Cox

I use PrintWriter class:

PrintWriter pw = new PrintWriter(new FileWriter("data.txt"));
pw.println(num);
pw.close();

Thanks Sharp - I have got this to work by adding as follows - but is
it better to put your code into a separate class? Beginner confusion!

Cheers

Geoff

public void stateChanged(ChangeEvent event)
{
JSlider src = (JSlider) event.getSource();
if(!src.getValueIsAdjusting())
position.setText("Position is
"+scale.getValue());

try
{
FileWriter outfile = new FileWriter ("data.txt");
PrintWriter pw = new PrintWriter(outfile);
pw.println(scale.getValue());
pw.close();
}
catch (IOException e) { System.out.println(e); }

}
 
S

Sharp Tool

Thanks Sharp - I have got this to work by adding as follows - but is
it better to put your code into a separate class? Beginner confusion!

Cheers

Geoff

No, it's not neccessary.

Cheers
Sharp
 

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

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top