Try with resources is available since java 7. So in order to use try with resources we need to go to Project Settings and set language level to 7.
Please note that in try with resources the code to close the file is not needed in finally block as that would be automatically taken care of
Another difference is in try/catch block if there are 2 errors one in try block while writing something to the file and one while closing the file then in try/catch block only the final error in finally block(one to close the file) is thrown back But in case of try with resources its the first error that is thrown back i.e one that happened while writing to the file and not the one that happened at time of closing the file
Please also note that try with resources allows more than one resource to be specified.So that means we can add a second file writer object inside the try block after we added the first one.
try( FileWriter locfile = new FileWriter("locations.txt");
FileWriter directionfile = new FileWriter("directions.txt");
)
{
for (location location : locations.values()) {
locfile.write(location.getLocationId() + "," + location.getDescription() + "\n");
// In the below code each location object we are getting a hashmap using getExits method and getting keys from that map and then wrting each
// location id and all directions for that id to a text file
for(String direction : location.getExits().keySet())
{
directionfile.write(location.getLocationId()+","+direction+","+location.getExits().get(direction)+"\n");
}
}
}
}