【问题标题】:How can I add non-text to a file?如何将非文本添加到文件中?
【发布时间】:2018-02-01 22:37:41
【问题描述】:

在保存游戏时,我想添加ints、Strings、booleans 等,因为这是我想要保存的游戏中的所有内容。唯一的问题是我能找到的只是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");
    }
}

【问题讨论】:

  • 将所有这些字段组合到一个类中并使用Serialization..
  • 您是要“将非文本添加到文件中”还是“将数字和字母添加到非文本文件中”,因为两者都在问题中?您可以尝试的一些事情是序列化或 JSON
  • 我喜欢@AlexK。回复。保存对象比编写然后解析文本文件要容易得多。亚历克斯+1哦,帕尔萨的回答+1。没看到。

标签: java file save


【解决方案1】:

您可以创建一个可序列化对象并将您的信息保存在该对象中,并将您的文件作为对象保存在.ser 可序列化文件中

导入 java.io.Serializable;

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();
    }
}

【讨论】:

  • 用你的文件路径,当你说save.ser时,你是在创建一个新文件吗?
  • 是的,当您使用 FileOutputStream 时,您会自动创建一个新文件,但其余部分是将对象插入该文件。如果您还需要提取它的方法,请告诉我,我会给您发送另一个答案
【解决方案2】:

也许您正在搜索二进制文件写入,例如这里: Java: How to write binary files?

在那里,您将数据以字节的形式直接写入磁盘。 另一种方法是将整数转换为类似

的字符
int integer = 65;    
char number = (char) integer; // outputting this will give you an 'A'
...
int loadedInt = (int) number; // loadedInt is now 65

char到int的转换表参考https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

除此之外,您必须在将对象写入文件之前将其转换为字符串(或任何其他类型的串行表示)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多