I have a BufferedWriter which writes into a file already, but not in the way I want to. I initialize it within a loop, causing it to append only the last result of the loop to get added to the file. Actually this is ok for me but the previous results in the file get deleted. I want the result getting added without deleting the previous results.
I tried to create static Buffered Reader in order to not always create new instances of Buffered Reader in the loop. But this is not possible since you need a "try" block.
public void actionPerformed(ActionEvent e) {
String s;
try {
if (parseInt(jTextFieldNumber.getText()) == random) {
info.setText("Attempt # " + counter + ": " +
parseInt(jTextFieldNumber.getText()) + " ==> correct!");
ok.setEnabled(false);
} else if (parseInt(jTextFieldNumber.getText()) < random)
{
info.setText("Attempt # " + counter + ": " +
parseInt(jTextFieldNumber.getText()) + " ==> too small!");
} else {
info.setText("Attempt # " + counter + ": " +
parseInt(jTextFieldNumber.getText()) + " ==> too big!");
}
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
System.exit(0);
}
s = jTextFieldName.getText() + " " + counter;
BufferedWriter bw;
try {
bw = new BufferedWriter(new
FileWriter("C:\\wrk\\SapCommerceCloud\\src\\SwingUni\\events1\\name"));
bw.append(s);
if(info.getText().equals("Attempt # " + counter + ":
" + parseInt(jTextFieldNumber.getText()) + " ==> correct!")){
bw.close();
}
} catch (IOException io) {
io.printStackTrace();
}
counter++;
}
};