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();
}
}
This
fOut = new FileOutputStream(file);will overwrite the file, you need to usefOut = new FileOutputStream(file, true);to append to it.