在保存游戏时,我想添加 int
、String
、boolean
等,因为这就是我游戏中的所有内容我想保存的。唯一的问题是我能找到的只是 how to add text to files?其中没有任何内容可以帮助您了解如何向非文本文件添加数字和字母。
现在,这是我的代码:
private void saveGame() {
try {
//Whatever the file path is.
File statText = new File("F:/BLAISE RECOV/Java/Finished Games/BasketBall/BasketballGame_saves/Games");
FileOutputStream is = new FileOutputStream(statText);
} catch (IOException e) {
System.err.println("Problem writing to the file statsTest.txt");
}
}
最佳答案
您可以创建一个可序列化对象,并将您的信息保存在该对象中,并将您的文件作为对象保存在 .ser
可序列化文件中
导入java.io.Serialized;
public class Save implements Serializable
{
private int i ;
private String s;
private boolean b;
public Save(int i, String s, boolean b)
{
this.i = i;
this.s = s;
this.b = b;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
public boolean isB() {
return b;
}
public void setB(boolean b) {
this.b = b;
}
}
你可以像这样保存对象:
public static void main(String[] args)
{
try
{
File file = new File("C:\\Users\\Parsa\\Desktop\\save.ser");
FileOutputStream output = new FileOutputStream(file);
ObjectOutputStream objectOutput = new ObjectOutputStream(output);
Save save = new Save(10,"aaa",true);
objectOutput.writeObject(save);
objectOutput.flush();
objectOutput.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
关于java - 如何向文件添加非文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48563563/