我有一款纸牌游戏,名叫“bluejack”。它有一个名为 HistoryManager 的类,该类创建名为 game_history.txt 的文件并将游戏分数写入该文件中。
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class HistoryManager{
public static final String FILE_PATH = "game_history.txt";
public static final int MAX_HISTORY_SIZE = 10;
public static void updateGameHistory(String gameResult) {
try (FileWriter fileWriter = new FileWriter(FILE_PATH, true);
BufferedWriter writer = new BufferedWriter(fileWriter)) {
writer.write(gameResult);
writer.newLine();
} catch (IOException e) {
System.err.println("Error occurred while updating game history: " + e.getMessage());
}
trimGameHistory();
}
public static void trimGameHistory() {
try (RandomAccessFile randomAccessFile = new RandomAccessFile(FILE_PATH, "rw")) {
long length = randomAccessFile.length();
if (length == 0) {
return;
}
int lineCount = countLines(randomAccessFile);
if (lineCount > MAX_HISTORY_SIZE) {
randomAccessFile.seek(0);
String line;
long newLength = 0;
int linesToDelete = lineCount - MAX_HISTORY_SIZE;
while ((line = randomAccessFile.readLine()) != null) {
if (linesToDelete > 0) {
linesToDelete--;
newLength += line.length() + 2;
}
}
randomAccessFile.setLength(newLength);
}
} catch (IOException e) {
System.err.println("Error occurred while trimming game history: " + e.getMessage());
}
}
public static String getCurrentDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
return dateFormat.format(new Date());
}
private static int countLines(RandomAccessFile file) throws IOException {
int lines = 0;
while (file.readLine() != null) {
lines++;
}
return lines;
}
}
当我使用 java Game.java 从 cmd 运行程序时,它可以工作,但是当它尝试创建 jar 文件时,游戏运行良好,但它不会创建任何文本,也不会编辑现有文本。
我问了chatgpt并在网上查找了它,但我找不到任何东西,我不知道解决它
我该如何解决这个问题,如果您能提供帮助,我会很高兴。
如果控制台没有任何IOError,可能是相对路径问题。检查
game_history.txt
是否与 jar 文件位于同一文件夹中。如果属实,请检查文件的访问权限。