简体   繁体   中英

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. I know it requires me to use a Try/Catch block, but I have no idea how to really handle it. 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.

Thanks for the help.

You are trying to write an object of type java.lang.Class to a file. If you want the String representation of the class name use toString():

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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