有没有一种方法可以检测文本而不覆盖它?

Is there a way where I can detect text and not overwrite it?

我正在努力写这个
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.")
到我的 scores.txt 文件中。
这就是我希望 scores.txt 文件中的输出看起来像:
在这里写保存然后跳行
在这里写保存然后跳过行(一遍又一遍地重复)

我的问题

每次我按下保存分数按钮时,它都会运行这段代码
myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.")
这很好。但是每当我再次按下保存分数按钮时,原始行就会被覆盖,这是我不希望发生的。

我试过的

我已经尝试了 \r\n 和 BufferedWriter,但它与我想要的结果不符。

我的代码

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
            }
        });
    }
}

如果你不想在每次需要追加的时候都覆盖文本。您可以按如下方式初始化 FileEriter 来完成此操作:

FileWriter myWriter = new FileWriter("scores.txt", true);

这个构造函数有两个参数,一个是你正在写入的文件,第二个是一个布尔表达式,它决定你是追加到文件还是覆盖它。

如果您想了解更多信息,可以在这里查看: https://www.geeksforgeeks.org/java-program-to-append-a-string-in-an-existing-file/