java - 如何向文件添加非文本?

标签 java file save

在保存游戏时,我想添加 intStringboolean 等,因为这就是我游戏中的所有内容我想保存的。唯一的问题是我能找到的只是 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/

相关文章:

c++ - 在不使用 C/C++ 使用第二个文件的情况下插入文件而不覆盖

java - 如何从 JLabel 保存图像

java - 使用 int 而不是 String : public static void main (int[] args)

java - 异常类名: org. springframework.context.NoSuchMessageException

java - 如何从 double 中删除尾随零

MySQL - 保存和加载项目的最佳方法

c++ - Winapi - SetWindowLongPtr 在 ShutdownBlockReasonCreate/Destroy 实现 JNI native 代码

java - 当我尝试删除对象时,Hibernate : org. hibernate.WrongClassException

Java:文件类型为 `url.openStream()`

php - jQuery.ajax 文件删除