I am trying to write this
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.")
onto my scores.txt file.
This is what I want the output in the scores.txt file to look like:
Write save here and then skip line
Write save here and then skip line (repeat again and again)
My Problem
Every time I press the save score button, it runs this code
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.")
which is good. But whenever I press the save score button again, the original line gets overwritten which I don’t want to happen.
What I’ve Tried
I have tried rn and BufferedWriter and it doesn’t match what I want the outcome to be.
My Code
HackerGUI.java
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; public class HackerGUI extends JFrame { //jframe components private JPanel rootPanel; private JButton hack; private JLabel time; private JButton reset; private JLabel description; private JLabel title; private JLabel gif; private JTextField textField1; private JButton saveScoresButton; private JButton settingsButton; private JButton placeholder; //timer stuff private final Timer timer; //create timer private final long duration = 10000; //duration of time private long startTime = -1; //start of the time private int delay = 300; //delay of when the time starts //hacker levels private int count = 0; public HackerGUI() { add(rootPanel); //add intellij windows builder form setTitle("Hacker UI v8.4"); //set the title of the frame try { File myObj = new File("scores.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); } else { System.out.println("Scores file already exists."); } } catch (IOException a) { System.out.println("An error occurred."); a.printStackTrace(); } try { File myObj = new File("settings.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); System.out.println("Absolute path: " + myObj.getAbsolutePath()); } else { System.out.println("Settings file already exists."); } } catch (IOException a) { System.out.println("An error occurred."); a.printStackTrace(); } timer = new Timer(20, new ActionListener() { //timer module @Override public void actionPerformed(ActionEvent e) { if (startTime < 0) { //if time reaches 0, stop time so it doesn't go to negative int startTime = System.currentTimeMillis(); //use system time } long now = System.currentTimeMillis(); //use system time long clockTime = now - startTime; if (clockTime >= duration) { //whenever clock reaches 0, run command under: clockTime = duration; timer.stop(); //stop the timer from going to the negatives hack.setEnabled(false); //disables hack button as timer went to 0 reset.setEnabled(true); //enable reset button to play again } SimpleDateFormat df = new SimpleDateFormat("mm:ss.SSS"); //format of time shown time.setText(df.format(duration - clockTime)); //set time component to destination } }); timer.setInitialDelay(delay); //set the delay hack.addActionListener(new ActionListener() { //play action listener, triggers when button is pressed @Override public void actionPerformed(ActionEvent e) { count++; //count in positives and add hack.setText("Hacker Level: " + count); //change int and label if (!timer.isRunning()) { //when button pressed, start timer startTime = -1; //int to when start timer.start(); //start } } }); reset.addActionListener(new ActionListener() { //reset action listener, triggers when button is pressed @Override public void actionPerformed(ActionEvent e) { hack.setEnabled(true); //enable hack button to start a new game reset.setEnabled(false); //disable reset button as it has been used //old command line save score String name = textField1.getText(); //get name string System.out.println(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds."); //print other info System.out.println(""); //print spacer //old command line save score count = count + -count; //count in positive integers hack.setText("Hacker Level: " + -count); //reset level score time.setText("00:10.000"); //reset time label } }); saveScoresButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { FileWriter myWriter = new FileWriter("scores.txt"); String name = textField1.getText(); //get name string myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds."); myWriter.close(); System.out.println("Successfully wrote to the score file."); } catch (IOException b) { System.out.println("An error occurred."); b.printStackTrace(); } } }); settingsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO: put stuff here } }); //please don't delete! as this shows credits and help info JOptionPane.showMessageDialog(rootPanel, "Hacker UI v8.4 is created by _._#3324, thank you for downloading! What is Hacker UI v8.4? It is a clicker game! To know more, read the documentation! https://github.com/udu3324/Hacker-UI-v8.4"); System.out.println("Hacker UI v8.4: has successfully loaded."); System.out.println("====================================================="); System.out.println(""); } private void createUIComponents() { // TODO: place custom component creation code here } public void setData(HackerGUI data) { } public void getData(HackerGUI data) { } public boolean isModified(HackerGUI data) { return false; } }
Main.java
import javax.swing.*; import java.net.URL; import java.util.Arrays; public class Main { public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, javax.swing.UnsupportedLookAndFeelException { System.out.println("Hello, World!"); //Hello, World! } UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { System.out.println("Hacker UI v8.4: is loading..."); //print status of loading URL iconURL = getClass().getResource("/images/Hacker UI.png"); //load icon resource ImageIcon icon = new ImageIcon(iconURL); //set icon to icon HackerGUI hackergui = new HackerGUI(); //make a hacker gui hackergui.setIconImage(icon.getImage()); //get icon resource and set as hackergui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //terminate when asked on close hackergui.setResizable(false); //no resizing hackergui.pack(); //wrap it into a pack and set jframe size depending on jframe component size hackergui.setLocationRelativeTo(null); //set location to middle of screen hackergui.setVisible(true); //set the frame visible } }); } }
Advertisement
Answer
If you do not want to overwrite the text each time you need to append. You can do this by initializing your FileEriter as follows:
FileWriter myWriter = new FileWriter(“scores.txt”, true);
This constructor takes 2 parameters, one is the file you are writing to and the second is a boolean expression that determines will you append to the file or overwrite it.
If you want to know more about it you can check it out here: https://www.geeksforgeeks.org/java-program-to-append-a-string-in-an-existing-file/