I need to write a method to take an array of objects and serialize them into a file. My question is how do I check to see if the file is there and if the file is not, it will create a file then serialize the objects to it?
Asked
Active
Viewed 1,977 times
-2
-
And if it is there? – user207421 Feb 23 '18 at 21:19
-
**Check this link out** Posible duplicate of this question – smacaz Feb 23 '18 at 21:24
-
@smacaz Duplicate of a small part of this question. – user207421 Feb 23 '18 at 21:26
-
@smacaz take a look at [this](https://meta.stackexchange.com/a/61072) ;) – Cardinal System Feb 23 '18 at 21:29
4 Answers
2
As long as the object is serializable, and you have Apache Commons OI and Apache Commons Lang, you can use SerializationUtils
and FileUtils
:
File file = new File(<file>)
if(!file.exists()){
FileUtils.writeByteArrayToFile (file, SerializationUtils.serialize(<obj>));
}

Cardinal System
- 2,749
- 3
- 21
- 42

Sashi
- 1,977
- 16
- 15
1
Use File#exists
and File#createNewFile
:
File file = new File("C:/...");
if(file.exists()){
// ...
} else {
file.createNewFile();
// ...
}

Cardinal System
- 2,749
- 3
- 21
- 42
-
Yes, so if this program is ran on another users console it can read it from the program and not from a path stored on the computer. Does that make sense? Thanks for the feedback! – Quinton Thompson Feb 23 '18 at 21:24
-
@QuintonThompson you can read a resource file using `Class#getResourceAsStream(String)`, although *creating* a resource file is a whole nother topic. See [Add files in jar during runtime](https://stackoverflow.com/questions/6763449/add-files-in-jar-during-runtime) – Cardinal System Feb 23 '18 at 21:27
-
1@QuintonThompson So when you clearly say 'file' in your question you now mean 'not a file'. Please clarify. – user207421 Feb 23 '18 at 21:27
-
1
Besides new File("path").exists()
, that has already been pointed out there is Files.exists(path)
that takes the Path
object that you will need to construct. Which one you want to use depends on the way the file path arrives in your application (whichever is simpler is the correct solution for you).

v010dya
- 5,296
- 7
- 28
- 48
-1
Using Java 8 File API
final Path path = Paths.get(URI.create("file:/C:/temp/test.txt"));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final ObjectOutputStream objOut = new ObjectOutputStream(out);
// add your objects here
objOut.writeObject(new Object());
Files.write(path, out.toByteArray(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);

IEE1394
- 1,181
- 13
- 33