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

zrfyljdw  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(393)

已解决

谢谢多拉·贝罗尼克帮我解决问题。我所做的是将scores.txt中已有的数据添加到我编写的字符串中。

新代码

黑客界面.java

saveScoresButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    FileWriter myWriter = new FileWriter("scores.txt", true);
                    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." + "\n");
                    myWriter.close();
                    System.out.println("Successfully wrote to the score file.");
                } catch (IOException b) {
                    System.out.println("An error occurred.");
                    b.printStackTrace();
                }
            }
        });

我的目标

我在写这个 myWriter.write(name + " has scored " + count + " hacker levels in " + duration +" milli-seconds with a delay of " + delay + " milli-seconds.") 到我的scores.txt文件。
我希望scores.txt文件中的输出如下所示:
在此处写入save,然后跳过行
在此处写入save,然后跳过行(重复一次又一次)

我的问题

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

我试过的

我尝试了\r\n和bufferedwriter,但结果与我想要的结果不匹配。

我的代码

黑客界面.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;
    }

    }

主.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
            }
        });
    }
}
jchrr9hc

jchrr9hc1#

如果不希望每次需要追加时都覆盖文本。您可以通过如下方式初始化fileeriter来完成此操作:
filewriter mywriter=new filewriter(“scores.txt”,true);
这个构造函数有两个参数,一个是您要写入的文件,第二个是一个布尔表达式,它决定您是附加到文件还是覆盖它。
如果您想了解更多信息,可以在此处查看:https://www.geeksforgeeks.org/java-program-to-append-a-string-in-an-existing-file/

相关问题