Open pangiann opened 2 years ago
Let's say that we want to create a new Dictionary and save it to a new file. To do so, we need to create the file.
To achieve we're going to exploit the File
Java class.
First we need to create a new File object which is an abstract representation of file and directory pathnames.
It takes as an argument a String
which represents the pathname of the file.
This class has a method called createNewFile
.
createNewFile atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.
In this way we can easily create our new dictionary file.
.medialab/<book_id>.txt
fileNotice here that in our case we don't want to create the file in the current working directory.
This makes it a bit more complex, because we cannot be sure if the parent directory (here .medialab
) exists.
But let's take a step back:
.medialab/<book_id>.txt
argument.In order to write to our file we follow the below steps:
FileWriter
which will write to the file. BufferedWriter
which accelerates the IO procedure suing buffering mechanism. PrintWriter
to use Print mechanisms like println etc.
In the Dictionary class implementation of the Hangman game we need to play with files. Specifically there are 2 cases: