04_Handout_1(35)
04_Handout_1(35)
Figure 1. Path location example. Retrieved from Farrell, J. (2023). Java programming, 10th edition. Cengage.
The illustration shows the complete path for a Windows file named Data.txt, saved on the C drive in a folder
named Chapter.11, which is within a folder named Java. The backslash (\) in the Windows operating system
is the path identifier which separates the path components. A slash (/) is used as the delimiter in the Solaris
(UNIX) operating system.
The following tasks are typically performed when working with stored files in an application:
o Determining whether and where a path or file exists
o Opening a file
o Writing to a file
o Reading from a file
o Closing a file
o Deleting a file
Java provides the path and files classes to work with stored files.
The Path and Files Classes
The Path class creates objects containing information about files and directories, including their locations,
sizes, creation dates, and whether they exist. On the other hand, the Files class performs operations on
files and directories, including deletion, determining their attributes, and creating input and output streams.
The import java.nio.file.*; statement can be included in a Java program to use both the Path and Files
classes. The nio in java.nio stands for new input/output as its classes are “new”.Creating a Path
Creating a Path can be initiated by determining the file system on the host computer by using a statement
such as the following:
FileSystem fs = FileSystems.getDefault();
This statement creates a FileSystem object using the getDefault() method in the FileSystems class.
It uses two (2) different classes: FileSystem class, without an ending s, to instantiate the object, and the
FileSystems class, with an ending s, which contains factory methods. In object-oriented programming
(OOP), a factory is an object that creates other objects.
After a FileSystem object is created, a Path can be defined using the getPath() method with it:
Path filePath = fs.getPath("C:\\Java\\Chapter.11\\Data.txt");
As mentioned, a backslash (\) is used as an escape sequence in Java. To enter it as a path delimiter within a
string, two (2) backslashes should be typed to indicate a single backslash.
Another way to create a Path is using the Paths class (with an ending s). The Paths class is considered a
helper class that eliminates the need to create a FileSystem object. The get() method of this class calls the
getPath() method of the default file system without requiring a FileSystem object. A Path object can be
created using the following statement:
Path filePath = Paths.get("C:\\Java\\Chapter.11\\SampleFile.txt");
After the Path is created, use its identifier, filePath in this case, to refer to the file and perform operations
on it. The C:\Java\Chapter.11\SampleFile.txt is the full name of a stored file when the operating system
refers to it, but the path is known as filePath within the application.
A Path’s elements are accessed using an index. The top-level element in the directory structure is located at
index 0, while the lowest element in the structure is accessed by the getName() method. This has an index
of one (1) less than the number of items on the list.
The getNameCount() method retrieves the number of names in the list, while the getName(int) method
retrieves the name in the position specified by the argument.
The program, PathDemo class, below shows a demonstration program that creates a Path and uses some of
the mentioned methods.
import java.nio.file.*;
public class PathDemo {
public static void main(String[] args) {
Path filePath = Paths.get("C:\\Java\\Chapter.11\\Data.txt");
int count = filePath.getNameCount();
System.out.println("Path is " + filePath.toString());
System.out.println("File name is " + filePath.getFileName());
System.out.println("There are " + count + " elements in the file path");
for(int x = 0; x < count; ++x)
System.out.println("Element " + x + " is " + filePath.getName(x));
}
}
The execution of this program:
The program, PathDemo3 class, below shows an application that declares a Path and checks whether a file
named there can be both read and executed. Notice that the java.io.IOException package must also be
imported.
import java.nio.file.*;
import static java.nio.file.AccessMode.*;
import java.io.IOException;
public class PathDemo3 {
public static void main(String[] args) {
Path filePath = Paths.get("C:\\Java\\Chapter.11\\PathDemo.class");
System.out.println("Path is " + filePath.toString());
try {
filePath.getFileSystem().provider().checkAccess(filePath, READ, EXECUTE);
System.out.println("File can be read and executed");
}
catch(IOException e) {
System.out.println("File cannot be used for this application");
}
}
}
The execution of this program:
System.out.println("IO Exception");
}
}
}
The time methods in the PathDemo4 program return a FileTime object converted to a String in the
println() method calls. FileTime objects are represented in the format: yyyy-mm-ddThh:mm:ss
The execution of this program:
In a FileTime object, the four-digit year is followed by a hyphen (-), the two-digit month, another hyphen,
and the two-digit day. Following a T for Time, the hour, minute, and seconds, even fractions of a second, are
separated by colons (:).
The IO Classes
The illustration below shows a partial hierarchical relationship of some of the classes Java uses for input and
output (IO) operations.
Figure 2. IO operations. Retrieved from Farrell, J. (2023). Java programming, 10th edition. Cengage.
The hierarchy shows that InputStream, OutputStream, and Reader are subclasses of the Object class.
The table below lists the capabilities and descriptions of selected classes used for input and output.
Classes Description
InputStream An abstract class that contains methods for performing input
FileInputStream Child of InputStream that provides the capability to read from disk files
BufferedInputStream Child of FilterInputStream that handles input from a system’s standard (or
default) input device, usually the keyboard
OutputStream An abstract class that contains methods for performing output
FileOutputStream Child of OutputStream that allows writing to disk files
BufferedOutputStream Child of FilterOutputStream that handles output from a system’s standard
(or default) output device, usually the monitor
PrintStream Child of FilterOutputStream. Java’s System class contains a PrintStream
object named System.out
Reader Abstract class for reading character streams; the only methods that a subclass
must implement are read(char[], int, int) and close()
BufferedReader Reads text from a character-input stream, buffering characters to provide for
efficient reading of characters, arrays, and lines
BufferedWriter Writes text to a character-output stream, buffering characters to provide for
the efficient writing of characters, arrays, and lines
The table below lists some of the OutputStream methods.
OutputStream Methods Description
void close() Closes the output stream and releases any system resources associated with
the stream
void flush() Flushes the output stream; if any bytes are buffered, they will be written
void write(byte[] b) Writes all the bytes to the output stream from the specified byte array
void write(byte[] b, Writes bytes to the output stream from the specified byte array starting at
int off, int len) offset position off for a length of len characters
The program, ScreenOut class shows an application declaring a String of letter grades allowed in a course.
import java.io.*;
public class ScreenOut {
public static void main(String[] args) {
String s = "ABCDF";
byte[] data = s.getBytes();
OutputStream output = null;
try {
output = System.out;
output.write(data);
output.flush();
output.close();
}
catch(Exception e) {
System.out.println("Message: " + e);
}
}
}
Then, the getBytes() method converts the String to an array of bytes. An OutputStream object is
declared, and System.out is assigned to the OutputStream reference in a try block. Lastly, the write()
method accepts the byte array and sends it to the output device, and then the output stream is flushed and
closed.
The execution of this program:
Reference:
Farrell, J. (2023). Java programming, 10th edition. Cengage.