如何处理为一个简单的Java游戏保存游戏数据

huangapple go评论57阅读模式
英文:

How to handle saving game data for a simple Java game

问题

我正在制作扫雷游戏的克隆版本,我希望用户能够将他们最快解决的时间保存到.txt文件中。我已经在Eclipse中的我的i/o类中设置并使用以下代码来实现:

public static final String RECORD_FILE_NAME = "records/records.txt";

public static String readRecords() {
    String records = "";
    
    try {
        Scanner scan = new Scanner(new FileInputStream(RECORD_FILE_NAME));
        while (scan.hasNextLine()) {
            records = records + scan.nextLine() + "\n";
        }
        scan.close();
        
    } catch (Exception e) {
        throw new IllegalArgumentException("无效的文件");
    }
    return records;
}

public static void writeRecords(String records, String fileName) {
    try {
        PrintStream writer = new PrintStream(new File(fileName));
        writer.print(records);
    } catch (Exception e) {
        throw new IllegalArgumentException("无法保存文件。");
    }
}

然而,在将项目导出为可运行的JAR文件后,readRecords() 方法会抛出 catch 块中的 IllegalArgumentException 异常。那么,我应该如何设置文件输入/输出,以便它在Eclipse之外也能工作?非常感谢任何帮助!

英文:

Im working on a Minesweeper clone and I want the user to be able to save their fastest solve times to a .txt file. I have it set up and working inside Eclipse with the following code in my i/o class:


        public static final String RECORD_FILE_NAME = "records/records.txt";

	public static String readRecords() {
		String records = "";
		
		try {
			Scanner scan = new Scanner(new FileInputStream(RECORD_FILE_NAME));
			while (scan.hasNextLine()) {
				records = records + scan.nextLine() + "\n";
			}
			scan.close();
			
		} catch (Exception e) {
			throw new IllegalArgumentException("Invalid file");
		}
		return records;
	}

	public static void writeRecords(String records, String fileName) {
		try {
			PrintStream writer = new PrintStream(new File(fileName));
			writer.print(records);
		} catch (Exception e) {
			throw new IllegalArgumentException("Unable to save file.");
		}
	}


However, after exporting the project as a Runnable JAR File, the readRecords() method throws the IllegalArgumentException from inside the catch block. So, how should I set up file i/o so that it works outside of Eclipse? Any help is greatly appreciated, thanks!

答案1

得分: 0

以下是翻译好的内容:

要注意的一些事情:

如果您想安全地打开文件,请使用try-with-resources块

try (PrintStream writer = new PrintStream(new File(fileName))) {
    writer.print(records);
}

您当前的方式可能不会关闭文件,因为写入器从未关闭,特别是在捕获异常时抛出错误

其次,我认为在这里抛出IllegalArgumentException并不是最佳选择,因为您基本上只是隐藏了可能的问题,而不是提供有用的堆栈跟踪,您只会得到"无法保存文件"。如果抛出的不是IO异常,这尤其是有问题的,因为它将隐藏其他异常(例如,如果其中某个方法不是空安全的,以某种方式抛出了空指针异常)

回答您的问题,records/records.txt 是一个相对文件位置,可能会更改
最好选择一个资源路径文件更多示例) 或一个通用文件(稍微不那么理想,因为它依赖于平台),或者使用MadProgrammer提到的通用位置方法

英文:

A couple things to mention here:

If you want to open files safely, use a try-with-resources block

try (PrintStream writer = new PrintStream(new File(fileName))) {
    writer.print(records);
}

The way you're currently doing it may not close the file since the writer is never closed, especially if an error is thrown upon catching an exception

Second, I don't think throwing an IllegalArgumentException is optimal here since you're essentially just hiding what the may be and instead of a helpful stacktrace you get just "Unable to save file.". This is epecially problematic if something other than an IO exception is thrown, as it will just hide it (e.g. if one of those methods isn't null-safe and somehow a nullpointerexception gets thrown)

To answer your question, records/records.txt is a relative file location, and may change
You'd best either go with a resource path file (extra examples) or a common file (a little less nice since it's platform-dependent), or the common locations method mentioned by MadProgrammer

答案2

得分: 0

这是如何在Java中创建和读取.txt文件的教程。您可以使用这个来读写游戏数据。

以下是来自该网站的代码:

import java.io.File;  // 导入 File 类
import java.io.IOException;  // 导入 IOException 类以处理错误

public class CreateFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      if (myObj.createNewFile()) {
        System.out.println("文件已创建:" + myObj.getName());
      } else {
        System.out.println("文件已存在。");
      }
    } catch (IOException e) {
      System.out.println("发生错误。");
      e.printStackTrace();
    }
  }
}
英文:

You can maybe save a text file with the needed data but this might help. This is how I store data like high scores in my game

This tutorial shows you how to create and read .txt files in Java. You could use this to read/write game data.

Here is the code from the website:

import java.io.File;  // Import the File class
import java.io.IOException;  // Import the IOException class to handle errors

public class CreateFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      if (myObj.createNewFile()) {
        System.out.println("File created: " + myObj.getName());
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

huangapple
  • 本文由 发表于 2023年4月17日 09:30:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031157.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定