pangiann / hangman

Hangman is a paper and pencil guessing game for two or more players.
0 stars 0 forks source link

[java-files] Document everything related to files in Java #3

Open pangiann opened 2 years ago

pangiann commented 2 years ago

In the Dictionary class implementation of the Hangman game we need to play with files. Specifically there are 2 cases:

  1. When we create a new Dictionary, we store its words into a new file.
  2. When we want to load a Dictionary, we load the words from the corresponding file.
pangiann commented 2 years ago

Create new file

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.

pangiann commented 2 years ago

Steps to create the .medialab/<book_id>.txt file

Notice 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:

  1. Create a new File object with the filepath (".medialab") as argument.
  2. Get the absolute path of this File object.
  3. Check the existence of the file.
    • If it does not exist: create a new directory using mkdirs()
  4. Create a File object with .medialab/<book_id>.txt argument.
  5. Create new File with the above pathname.
pangiann commented 2 years ago

Write dictionary content to the newly created file

In order to write to our file we follow the below steps:

  1. Create a new FileWriter which will write to the file.
  2. Create a new BufferedWriter which accelerates the IO procedure suing buffering mechanism.
  3. Create a new PrintWriter to use Print mechanisms like println etc.
  4. Get the words (Strings) by iterating through our dictionary Set.
  5. Write the words with a newline in the file.