代码之家  ›  专栏  ›  技术社区  ›  user9010885

如何向文件中添加非文本?

  •  2
  • user9010885  · 技术社区  · 7 年前

    在保存游戏时,我想添加 int s String s boolean s、 等等,因为这是我比赛中想要保存的一切。唯一的问题是我能找到的 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");
        }
    }
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   parsa    7 年前

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

    导入java。io。可序列化;

    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();
        }
    }
    
        2
  •  0
  •   Adrian Kiesthardt    7 年前

    也许您正在搜索二进制文件写入,如以下所示: 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
    

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

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