Advanced Programming ch2
Advanced Programming ch2
SYSTEMS PROGRAMMING
FILE DESCRIPTOR
■ File streams can be used to input and output data as bytes or characters.
■ Streams that input and output bytes are known as byte-based streams, representing data in
■ Streams that input and output characters are known as character-based streams,
■ Files that are created using byte-based streams are referred to as binary files.
■ Binary files are read by programs that understand the specific content of the file and the
■ A Java program opens a file by creating an object and associating a stream of bytes or
■ Class System provides methods setIn, setOut and setErr to redirect the standard input, output
■ Java programs perform file processing by using classes from package java.io.
■ You open a file by creating an object of one these stream classes. The object’s
13
CLASS FILE
■ A directory in Java is treated simply as a File with one additional property—a list of
filenames that can be examined by the list( ) method.
■ Class File provides four constructors.
– File(String directoryPath)
– File(String directoryPath, String filename)
– File(File dirObj, String filename)
– File(URI uriObj)
■ The one with a String argument specifies the name of a file or directory to associate
with the File object.
– The name can contain path information as well as a file or directory name.
– A file or directory’s path specifies its location on disk.
– An absolute path contains all the directories, starting with the root directory, that
lead to a specific file or directory.
– A relative path normally starts from the directory in which the application began
executing and is therefore “relative” to the current directory.
CLASS FILE (CONT.)
■ The SECOND constructor with two String arguments specifies
■ The THIRD constructor with File and String arguments uses an existing File object that
specifies the parent directory of the file or directory specified by the String argument.
– A Uniform Resource Identifier (URI) is a more general form of the Uniform Resource
Locators (URLs) that are used to locate websites.
■ http://download.oracle.com/javase/6/docs/api/java/io/File.html
METHODS
■ File defines many methods that obtain the standard properties of a
File object.
■ For example,
– getName( ) returns the name of the file;
– getParent( ) returns the name of the parent directory; and
– exists( ) returns true if the file exists, false if it does not.
16
EXAMPLE
17
CLASS FILE (CONT.)
27
EXAMPLE
28
THE LISTFILES( ) ALTERNATIVE
■ There is a variation to the list( ) method, called listFiles( ), which you might find
useful.
■ The signatures for listFiles( ) are shown here:
– File[ ] listFiles( )
– File[ ] listFiles(FilenameFilter FFObj)
– File[ ] listFiles(FileFilter FObj)
■ These methods return the file list as an array of File objects instead of strings.
■ The first method returns all files, and
■ the second returns those files that satisfy the specified FilenameFilter.
■ The third version of listFiles( ) returns those files with path names that satisfy the specified
FileFilter.
■ FileFilter defines only a single method, accept( ), which is called once for each file in a list.
– The accept( ) method returns true for files that should be included in the list (that is,
those that match the path argument) and false for those that should be excluded.
29
CREATING
DIRECTORIES
■ Another two useful File utility methods are mkdir( ) and mkdirs( ).
■ The mkdir( ) method creates a directory, returning true on success
and false on failure.
– Failure can occur for various reasons, such as the path specified in
the File object already exists, or the directory cannot be created
because the entire path does not exist yet.
■ To create a directory for which no path exists, use the mkdirs( )
method. It creates
30
I/O EXCEPTIONS
■ Two exceptions play an important role in I/O handling.
– The first is IOException.
– if a file cannot be opened, a FileNotFoundException is thrown.
■ FileNotFoundException is a subclass of IOException, so both can be
caught with a single catch that catches IOException.
31
READ & WRITING
FILES
CONT …
■ Java provides a number of classes and methods that allow you to read and write
files.
■ Here, fileName specifies the name of the file that you want to open.
33
CONT…
■ When you create an input stream, if the file does not exist, then
FileNotFoundException is thrown.
■ For output streams, if the file cannot be opened or created, then
FileNotFoundException is thrown.
■ FileNotFoundException is a subclass of IOException.
■ When an output file is opened, any preexisting file by the same name is
destroyed.
■ When you are done with a file, you must close it.
■ This is done by calling the close( ) method, which is implemented by both
FileInputStream and FileOutputStream. It is shown here:
34
FILEINPUTSTREAM
■ The FileInputStream class creates an InputStream that you can use to read
bytes from a file.
■ Two commonly used constructors are shown here:
FileInputStream(String filePath)
FileInputStream(File fileObj)
■ To read from a file, you can use a version of read( ) that is defined within
FileInputStream.
■ The one that we will use is shown here:
int read( ) throws IOException
■ Each time that it is called, it reads a single byte from the file and returns the
byte as
an integer value. read( ) returns –1 when an attempt is made to read at the
end of the
stream.
■ It can throw an IOException.
35
FILEOUTPUTSTREAM
■ FileOutputStream creates an OutputStream that you can use to write bytes to a
file.
■ It implements the AutoCloseable, Closeable, and Flushable interfaces.
■ Four of its constructors are shown here:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
■ They can throw a FileNotFoundException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file. If append is true, the file is
opened in append mode.
– FileReader(String filePath)
– FileReader(File fileObj)
■ File locking is a mechanism that allows you to prevent multiple processes or threads from
concurrently accessing or modifying the same file.
■ In Java, you can use the java.nio.channels package to lock a file or a portion of a file.
■ There are two types of file locks: shared locks and exclusive locks.
■ A shared lock allows multiple processes or threads to read from the locked file, but only one process
or thread can hold an exclusive lock, which allows it to read from and write to the locked file.
FILE LOCKING …
■ Here's an example of how to obtain a file lock in Java :
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class FileLockExample {
public static void main(String[] args) throws Exception {
RandomAccessFile file = new RandomAccessFile("myFile.txt",
"rw");
FileChannel channel = file.getChannel();
// Obtain an exclusive lock on the entire file
FileLock lock = channel.lock();
// Do some work with the file // ... // Release the lock lock.release();
channel.close();
file.close();
PROCESS
CREATING PROCESSES
■ In Java, you can create a new process using the ProcessBuilder or Runtime class.
■ Both classes provide a way to execute an external program as a separate process from your
Java application.
■ Here's an example of how to use ProcessBuilder to create a new process:
import java.io.*;
public class CreateProcessExample {
public static void main(String[] args) throws IOException, InterruptedException
{ // Create a ProcessBuilder instance for the external program
ProcessBuilder processBuilder = new ProcessBuilder("notepad.exe", "test.txt"); // Start the external program
Process process = processBuilder.start(); // Wait for the process to finish
int exitCode = process.waitFor(); // Print the exit code of the process
System.out.println("Process exited with code " + exitCode);
}
}
CONT…
import java.io.*;
public class PipeExample {
public static void main(String[] args) throws IOException {
// Create a PipedInputStream and a PipedOutputStream
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream(in);
// Write some data to the output stream
out.write("Hello, world!".getBytes());
PIPEEXAMPLE
■ In this example, we create a signal handler that prints a message when a signal is
received.
■ We register the signal handler for the TERM signal using the Signal.handle() method,
and then wait for the TERM signal using the Thread.sleep() method.
■ Note that signal handling is not recommended for general use in Java, and should be
used only when necessary.
■ Also note that the Signal class is not part of the public API and may not be available on
all platforms.
MEMORY-MAPPED I/O
■ Memory-mapped I/O (MMIO) is a technique for accessing hardware devices from a computer
program by mapping device registers into the computer's address space, allowing them to be
accessed as if they were normal memory locations.
■ This buffer can be created using the java.nio.MappedByteBuffer class, which provides
methods for reading and writing to the mapped buffer.
■ A SecurityException occurs if the user does not have permission to write data to
the file.
■ A FileNotFoundException occurs if the file does not exist and a new file cannot
be created.
■ static method System.exit terminates an application.
– An argument of 0 indicates successful program termination.
– A nonzero value, normally indicates that an error has occurred.
– The argument is useful if the program is executed from a batch file on Windows or
a shell script on UNIX/Linux/Mac OS X.
CREATING A SEQUENTIAL-ACCESS TEXT
FILE (CONT.)
■ The application in Figs. 17.9 and 17.10 reads records from the file "clients.txt"
created by the application of Section 17.4.1 and displays the record contents.
READING DATA FROM A SEQUENTIAL-
ACCESS TEXT FILE
■ To retrieve data sequentially from a file, programs start from the beginning of the file
and read all the data consecutively until the desired information is found.
■ It might be necessary to process the file sequentially several times (from the beginning
of the file) during the execution of a program.
■ Class Scanner does not allow repositioning to the beginning of the file.
– The program must close the file and reopen it.
UPDATING SEQUENTIAL-ACCESS FILES
■ The data in many sequential files cannot be modified without the risk of
destroying other data in the file.
■ If the name “White” needed to be changed to “Worthington,” the
old name cannot simply be overwritten, because the new name requires
more space.
■ Fields in a text file—and hence records—can vary in size.
■ Records in a sequential-access file are not usually updated in place.
Instead, the entire file is usually rewritten.
■ Rewriting the entire file is uneconomical to update just one record, but
reasonable if a substantial number of records need to be updated.