Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving objects with Java

Tags:

java

io

I have a question about the following code. I create three instances of my Player class, and then I save them to a file.

Player a = new Player(1, "asd");
Player b = new Player(2, "asd");
Player c = new Player(3, "asd");

try {
    FileOutputStream fos = new FileOutputStream("Game.ser");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeObject(a);
    oos.writeObject(b);
    oos.writeObject(c);

    oos.close();
} catch (IOException e) {
    e.printStackTrace();
}

What happens with Game.ser? Is this a file that's actually created, or is it just within the program? If not, where is it located? I don't find it in any project folder.

The program works fine. Im just wondering about where the objects are saved.

like image 585
lawls Avatar asked Mar 03 '26 02:03

lawls


2 Answers

They're saved in the application path. You can use

new File("Game.ser").getAbsolutePath()

to display their location

like image 177
Reimeus Avatar answered Mar 05 '26 15:03

Reimeus


If the path provided in

FileOutputStream fos = new FileOutputStream("Game.ser");

is not absolute, it is created/opened relative to the folder the java application was launched from.

In an IDE like Eclipse, the application is usually ran from your Project directory. If your project is in, for example

C:\Users\You\workspace\MyApplication

the file would be created in

C:\Users\You\workspace\MyApplication\Game.ser

You can get that path by running

System.getProperty("user.dir");

The path your provide to the FileOutputStream, if it isn't absolute, will be relative to that.

like image 22
Sotirios Delimanolis Avatar answered Mar 05 '26 14:03

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!