Reputation: 109
I'm learning java and I have made simple program that simply reads value from JTextField and saves it to file using FileOutputStream.
My question is: is it normal for data to be unreadable (using same program with FileInputStream) after restarting it? If i read it without terminating program it works fine.
How can I make data wrote to file permament?
Edit:
It seems the file is being cleaned when starting the program.
Here is the code:
public class Test extends JFrame
{
JTextField field;
JButton write;
JButton read;
File file;
FileOutputStream fOut;
FileInputStream fIn;
int x;
Test() throws IOException
{
setAlwaysOnTop(true);
setLayout(new BorderLayout());
field = new JTextField(4);
write = new JButton("Write");
read = new JButton("Read");
file = new File("save.txt");
if(!file.exists())
{
file.createNewFile();
}
fOut = new FileOutputStream(file);
fIn = new FileInputStream(file);
add(field);
add(write, BorderLayout.LINE_START);
add(read, BorderLayout.LINE_END);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(160,60);
write.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
x = Integer.parseInt(field.getText());
try
{
fOut.write(x);
System.out.println("Saving completed.");
fOut.flush();
}
catch(Exception exc)
{
System.out.println("Saving failed.");
}
}
});
read.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
x = fIn.read();
fIn.close();
}
catch(Exception exc)
{
System.out.println("Reading failed.");
}
}
});
}
public static void main(String[] args) throws IOException
{
new Test();
}
}
Upvotes: 0
Views: 1217
Reputation: 3025
This fOut = new FileOutputStream(file);
will overwrite the file, you need to use fOut = new FileOutputStream(file, true);
to append to it.
Upvotes: 0
Reputation: 485
here's some code to open a file for writing .. observe the "true" parameter which means we APPEND the text at the end instead of adding it to the start. The same goes for FileOutputStream .. if you don't specify the second argument (true) you will end up with an overwritten file.
try{
// Create file
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (IOException e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
Upvotes: 0