开发者

When you serialize and save an object in java, Where is the file created?

When you开发者_如何学编程 save an object in java (using serialize), where is the file created?

For example if you used this method http://www.rgagnon.com/javadetails/java-0075.html


If you are using the ObjectOutputStream for serialization and wrapping it around a FileOutputStream then the objects will go into that file.

For example (from the ObjectOutputStream Javadoc):

FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeInt(12345);
oos.writeObject("Today");
oos.writeObject(new Date());

oos.close();

This will create a file "t.tmp" in the working directory of the java application.

And about the working directory... If you are using an IDE to launch your application then the working directory depends on where the IDE puts the compiled classes and how it runs your application.

You can use the following code to print the working directory:

File f = new File(".");
System.out.println(f.getAbsolutePath());

The "." represents the "current" directory.


Generally wherever you saved it to. How is the File created?


Update

From the link, it seems the code is creating a File by instantiating the file from aString representing the name, with no path. Others have addressed that.

Instead, I would like to stress the following. Do not create files there. If they are temporary files, put them in the temp directory, as already mentioned in another answer. If they are files the program might need to access later, put them in a stable & reproducible path, e.g. a sub-directory of user.home.

E.G. (pseudo-code, untested)

String name = "data.ser";
String[] pkgs = {"com", "our", "main"};
File f = new File(System.getProperty("user.home");
for (String pkg : pkgs) {
    f = new File(f, pkg);
}
f = new File(f, name);
...


If you mean the standard serialization using java.io.Serializable, then there is no "standard" location. Your rather create an instance of ObjectOutputStream that decorates an aribtrary OutputStream.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(someObject);
oos.close();

In this example, the object was written in-memory. If you use a FileOutputStream, then you could serialize your object to an arbitrary file.


Edit:

In your link, the resulting file will be stored in the "current working directory" which is the directory from where you executed your Java app using the java ... command.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜