Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 有没有一种方法可以检测文本而不覆盖它? 解决了的_Java_Filewriter - Fatal编程技术网

Java 有没有一种方法可以检测文本而不覆盖它? 解决了的

Java 有没有一种方法可以检测文本而不覆盖它? 解决了的,java,filewriter,Java,Filewriter,谢谢多拉·贝罗尼克帮我解决问题。 我所做的是将scores.txt中已有的数据追加,并将\n添加到我编写的字符串中 新代码 HackerGUI.java saveScoresButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try {

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

新代码 HackerGUI.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();
                }
            }
        });
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;
    }

    }
我的目标 我正试着写这个 myWriter.writename+在+持续时间+毫秒内获得+计数+黑客等级,延迟为+延迟+毫秒。 到我的scores.txt文件中。 我希望scores.txt文件中的输出如下所示: 在此处写入“保存”,然后跳过第行 在此处写入save,然后跳过行并反复重复

我的问题 每次我按下SaveScore按钮,它都会运行以下代码 myWriter.writename+在+持续时间+毫秒内获得+计数+黑客等级,延迟为+延迟+毫秒。 这很好。但每当我再次按下保存分数按钮时,原始行就会被覆盖,这是我不希望发生的

我试过的 我已尝试\r\n和BufferedWriter,但结果与我希望的结果不匹配

我的代码 HackerGUI.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();
                }
            }
        });
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;
    }

    }

如果不希望每次需要追加时都覆盖文本。您可以通过如下方式初始化文件服务器来完成此操作:

FileWriter myWriter=newfilewriterscores.txt,true

此构造函数接受两个参数,一个是要写入的文件,第二个是布尔表达式,用于确定是附加到文件还是覆盖文件

如果您想了解更多信息,可以在此处查看:

如果您不想在每次需要追加时覆盖文本。您可以通过如下方式初始化文件服务器来完成此操作:

FileWriter myWriter=newfilewriterscores.txt,true

此构造函数接受两个参数,一个是要写入的文件,第二个是布尔表达式,用于确定是附加到文件还是覆盖文件

如果您想了解更多信息,可以在此处查看: