Here we will be using read and write files using java.nio package which came available in java 1.4 to read and write objects to a file
The only difference using nio class will be that we will be passing an instance of Path Class rather than instance of file class as we used to do with io packages.
So for io packages we use
try (ObjectOutputStream locfile = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("locations2.dat")));) {
So what we doing with java nio method below we are doing is we create a file outputStream using Files.newOutputStream(locPath) and that is the only difference from java io package as in java io pacakge we were creating file using new FileOutputStream("locations2.dat")));)
Then we buffer the output using BufferedOutputStream so that data is written in buffers and then we wrap it in ObjectOutputStream so that we can write objects instead of normal data.
try(ObjectOutputStream locFile = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(locPath)))){
Compelete code to write objects to a file
public static void main(String[] args) throws IOException {
Path locPath = FileSystems.getDefault().getPath("locations.dat");
try(ObjectOutputStream locFile = new ObjectOutputStream(new BufferedOutputStream(Files.newOutputStream(locPath)))){
for (Location location : locations.values()) {
locFile.writeObject(location);
}
}
catch(IOException e){
e.printStackTrace();
}
}
Same way for reading data in static initialization block we pass instance of Path instead of instance of File like below
Path locPath = FileSystems.getDefault().getPath("locations.dat");
try (ObjectInputStream locfile = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(locPath)))) {
Compelete code is below
static {
Path locPath = FileSystems.getDefault().getPath("locations.dat");
try (ObjectInputStream locfile = new ObjectInputStream(new BufferedInputStream(Files.newInputStream(locPath)))) {
boolean endOfFile = false;
while (!endOfFile) {
try {
Location location = (Location) locfile.readObject();
//And once object is created we can access the methods of this class
System.out.println("Read location---> " + location.getLocationId() + " , " + location.getDescription());
} catch (EOFException e) {
endOfFile = true;
}
}
}
catch (InvalidClassException e) {
System.out.println("Invalid class exception ->"+e.getMessage());
}
catch (IOException e) {
System.out.println("IO exception ->"+e.getMessage());
}
catch (ClassNotFoundException e) {
System.out.println("Invalid class exception ->"+e.getMessage());
}
}