Section 8.1 Class Imports
File handling is an integral part of programming. Most programming languages have the ability to create, read from, write to, and delete, files. In Python, most built-in libraries are available without needing to explicitly import additional packages, but some libraries like
math do need to be imported. Listing 8.1.1 shows an example of importing the math library in Python.
Delete the first line that says
import math and see what happens. The import math is needed. The same program in Java would look like Listing 8.1.2.
Note the use of
import java.lang.Math; in the above to import the Math class. Unlike Python, Java requires explicit import for most libraries, including the Math class and many classes related to file handling.
Much like the
Math class, in order for your program to work with files you need use import. Java includes a class called File in the io library shown in Listing 8.1.3. This class allows you to create File objects, and use its public methods.
import java.io.File;
The
Scanner class from the util library will need to be imported if there is any need for a program to read a file as shown in Listing 8.1.4. It should be noted that this library is unnecessary if the program will not be reading any data from a file.
import java.util.Scanner;
The
FileWriter class can be used to write to files as shown in Listing 8.1.5. In the same way that the Scanner class isn’t needed unless the program will read from a file, the FileWriter class isn’t needed unless the program will write to a file.
import java.io.FileWriter;
Finally, these last two classes provide error handling and must be used in tandem with the
File class when reading from or writing to files as shown in Listing 8.1.6. IOException handles file creation and writing errors, while FileNotFoundException handles errors when trying to read files.
import java.io.IOException;
import java.io.FileNotFoundException;
You have attempted of activities on this page.
