简体   繁体   English

Java:将变量写入文件,然后回读

[英]Java: Writing Variables to File, and Reading back

I am currently using Eclipse Java Neon for my builder, and I am trying to implement a save and load feature into a project i am currently working on. 我目前正在将Eclipse Java Neon用于我的构建器,并且正在尝试将保存和加载功能实现到当前正在研究的项目中。 I know it requires me to use a Try/Catch block, but I have no idea how to really handle it. 我知道这需要我使用Try / Catch块,但是我不知道如何真正处理它。 Not only that, but what I tried out is giving me a bit of an error: 不仅如此,我尝试的方法还给我带来了一些错误:

    try {
        System.out.println("Writing to file...");
        charWrite = new FileWriter("player.dat");
        charWrite.write(player.getName()); //String
        charWrite.write(player.getJob()); //String
        charWrite.write(player.getLevel()); //Int
        charWrite.write(player.getCurrency()); //Int
        charWrite.write(player.getHealth()); //Int
        charWrite.write(player.getExp()); //Int
    }
    catch (IOException excpt) {
    System.out.println("Caught IOException: " + excpt.getMessage());
    }

The system seems to recognize what is happening, but when I go to open it and see if it has written, the document is still blank. 系统似乎可以识别正在发生的事情,但是当我打开它并查看它是否已写入时,该文档仍然为空白。

And if I am this lost on writing, I am going to be so lost when reading to place it into the Class's parameters. 如果我在写作时迷失了方向,那么在阅读并将其放入Class的参数中时,我将会迷失。

Thanks for the help. 谢谢您的帮助。

You are trying to write an object of type java.lang.Class to a file. 您正在尝试将类型为java.lang.Class的对象写入文件。 If you want the String representation of the class name use toString(): 如果要使用类名的String表示形式,请使用toString():

charWrite.write(player.getClass().toString());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM