Many software applications may require interaction with the file system to read or permanently store data on the machine. In this module, we will describe how files can be accessed in our Java programs.
Files in Java
Exercise 1: Accessing files
Using the information presented in the previous section, write a Java program that can create a File object to refer to a file that is stored in a given path. Using the File class methods, print the properties of this file including its path, file name, size and the last date it was modified.
Solution
Reading files
Exercise 2: Reading files
In this exercise, we can similarly create a File object referring to a given file in the file system, and further use the Scanner class methods to read the contents of the file. Please create a file with the given contents and print them inside your Java method.
Solution
We can implement a Java method that iterates through the lines of the file with the nextLine() method in the Scanner class.
Note that if we wanted to read each word separately, we could also use the next() method, which is sensitive to white space.
Writing to Files
Exercise 3: Writing to files
Let’s now try to practice writing to files using the FileWriter class in Java. You can create a File object referring to your output file destination, and use the write() method from the FileWriter class to write any text content into the output file.
Solution