Section 1
Lesson - 303.13 Java Files and Java IO
Learning Objectives:
In this lesson, we will demonstrate how to work with files in Java. By the end of lesson, learners will be able to:
Explain the Java IO Package.
Describe how to use the File API to access a file using absolute and relative paths.
Describe the difference between getPath() and getAbsolutePath() methods provided by the API.
Demonstrate how to access a directory.
Create a file.
Read a file.
Write content in a file.
Section 1: Java IO package and File Class
Table of Contents
Topic 1: Overview of Java IO package
Topic 2: Overview of File Class
Topic 2a: Why use Files?
Topic 2b: File Class Constructors
Topic 2c: Create File Class Object
Topic 2d: Absolute Path and Relative Path
Topic 2e: Methods for Absolute Path and Relative Path
Topic 2f: File Class Useful Method
Topic 2g: Creating Directories/Folders
Topic 2h: Reading File Content
Topic 2i: Reading a Delimited File
Topic 2j: Deleting File Using File Class
Topic 1: Overview of Java IO Package
The java.io package is primarily focused on input and output to files, network streams, internal memory buffers etc.
The java.io package contains many classes that your programs can use to read data from a source and write data to a destination.
The most typical sources and destinations of data include: Files, Pipes, Network Connections, In-memory Buffers (e.g., arrays), System.in, System.out, and System.error.
Topic 2: Overview of File Class
The File class of the java.io package is used to perform various operations on files.
We can access all of the characteristics of the file from our system through the File Class.
FileNotFoundException exception occurs while we try to access a file because of following reasons:
If the given file is not available in the given location, this exception will occur.
If the given file is inaccessible, such as a read-only file, you can read the file but not modify the file. If we try to modify it, an exception will occur. If the file that you are trying to access for the read/write operation is opened by another program, this error will occur.
For example, if you need to check whether a file has the appropriate directory name, you need the File class.
Topic 2a: Why use Files?
While variables and arrays can be stored in memory, the storage gets wiped out when your program is closed. In order to permanently store data, you will need to put it inside of a file.
Files are relatively insecure when compared to a database. Likewise, obtaining data from a file can take much more time than obtaining data from a database because no indexes exist.
Data that must be secured (such as user information) or stored in large quantities should be placed in a database rather than a file. For anything else (e.g., properties or basic storage), files can be used.
Topic 2b: File Class Constructors
To use a file, declare a File variable using one of its constructors:
File(String pathString)
File(String parent, String child)
File(File parent, String child)
File(URI uri)
Topic 2c: Create File Class Object
To create an Object of File class, we need to import the java.io.File package first.
Instances of a File class are immutable; once created, the abstract pathname represented by the File object will never change.
The basic syntax for creating a file object is: File <objectname> = new File(<Directory>)
Topic 2d: Absolute Path and Relative Path
In general, a path is a way to refer to a particular file or directory in a file system. There are two types of paths: absolute and relative.
Absolute Path: A path is absolute if it starts with the root element of the file system. In windows os, the root element is a drive (e.g. C:\\, D:\\), while in unix os, it is denoted by the “/” character. An absolute path is complete in that no other information is required to locate the file. It usually holds the complete directory list, starting from the root node of the file system until it reaches the file or directory it denotes.
Relative Path: A relative path is a path that does not start with the root element of the file system. It is simply the path needed in order to locate the file from within the current directory of your program. It is not complete and needs to be combined with the current directory path in order to reach the requested file.
Checking if a path is relative:
isAbsolute(): The isAbsolute() method is a part of File class. This method returns whether the abstract pathname is absolute or not.
Another useful method is getAbsolutePath(). It returns the absolute path to an instance of the file.
Topic 2e: Methods for Absolute Path and Relative Path
The File class has many useful methods for creating and getting information about files.
createNewFile(): To create a new file, we can use the createNewFile() method. It returns true if a new file is created and false if the file already exists in the specified location.
delete(): Removes the file or directory (if empty).
length(): Returns the file size in bytes.
exists(): Tells if the file or directory really exists in the file system.
canRead() and canWrite(): Tells if you can read or write to the file, respectively.
isFile() and isDirectory(): Tells if a file points to a file or directory, respectively.
list(): Return contents of the directory in a String-array.
listFiles(): Return contents of the directory in a File-array.
Topic 2f: File Class Useful Method
The File class has many useful methods for creating and getting information about files.
getParentFile(): Returns a file pointing to the directory that contains the current file or directory.
getAbsoluteFile(): Returns another instance of file with an absolute path.
toURI(): Returns a URI (Universal Resource Identifier) that begins with file, which is useful to network operations.
getFreeSpace(): Returns the available space in the device to where file is pointing to.
createTempFile(): Static method that returns a unique temporary file to be used by the application. The method deleteOnExit will delete the file at the termination of the program.
isHidden(): Returns true if a file or directory is hidden.
lastModified(): Returns the date when the file was last modified (in milliseconds); this value can be converted into the dd-MM-yyyy HH:mm:sss format using SimpleDateFormat class.
Topic 2g: Creating Directories/Folders
You can use the mkdir() or mkdirs() methods to create a new directory.
The mkdir() method creates a directory only if the parent directory specified in the pathname already exists.
The mkdir() method creates a directory returning true on success and false on failure.
Topic 2h: Reading File Content
One approach to reading a file is to make use of a Scanner Class. A Scanner Class supports tokens for all of the Java language primitive types (except for char).
Usually, we pass System.in to the Scanner in order to read user Input. Now, instead, we are going to pass in our file location.
To read a single character, we can use next().charAt(0).
The Scanner class provides methods like hasNextLine() and nextLine(), which can be used to read a file line-by-line until an "End of File" (EOF) character is reached.
Topic 2i: Reading a Delimited File
A delimited file is a file that has been separated into columns and rows (e.g., a table).
For separating a Delimited file, we can use String class - a split() method to identify the comma delimiter and split the row into fields or Scanner class - a useDelimiter() method to identify the comma delimiter and split the row into fields.
Topic 2j: Deleting File Using File Class
Use the delete() method of the File class to delete a file/directory. This method returns true if the file/directory is deleted; otherwise, it returns false.
You can also delay the deletion of a file until the JVM terminates by using the deleteOnExit() method.
Knowledge Checks
What package holds the File class?
Is the following path a relative path or an absolute path? C:\MyFiles\Programs\Examples\someFile.txt
What method of File class is used to test if a file or directory exists?
What File class method creates a new disk directory?
Last updated