[英]Is there a way where I can detect text and not overwrite it?
Thank you to Dora Beronic for helping me solve my question.感谢 Dora Beronic 帮助我解决了我的问题。 What I did was that I appended the data already inside of the scores.txt and added \n to my string written.我所做的是将数据附加到 score.txt 中,并将 \n 添加到我写入的字符串中。
HackerGUI.java 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();
}
}
});
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.到我的 score.txt 文件中。
This is what I want the output in the scores.txt file to look like:这就是我希望 score.txt 文件中的 output 看起来像的样子:
Write save here and then skip line在这里写保存然后跳行
Write save here and then skip line (repeat again and again)在这里写保存然后跳行(一次又一次地重复)
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.但是每当我再次按下保存分数按钮时,原始行就会被覆盖,这是我不希望发生的。
I have tried \r\n and BufferedWriter and it doesn't match what I want the outcome to be.我已经尝试过 \r\n 和 BufferedWriter ,但它与我想要的结果不符。
HackerGUI.java 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主.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
}
});
}
}
If you do not want to overwrite the text each time you need to append.如果不想每次都覆盖文字就需要append。 You can do this by initializing your FileEriter as follows:您可以通过如下初始化 FileEriter 来做到这一点:
FileWriter myWriter = new FileWriter("scores.txt", true); 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.这个构造函数有两个参数,一个是你正在写入的文件,第二个是一个 boolean 表达式,它决定你是 append 到文件还是覆盖它。
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/如果您想了解更多信息,可以在这里查看: https://www.geeksforgeeks.org/java-program-to-append-a-string-in-an-existing-file/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.