Java Reference
In-Depth Information
SUMMARY
In this chapter, I discussed the various ways in which you can read basic types of data from a file. You can
now transfer data of any of the basic types to or from a file. In the next chapter you will learn how to transfer
objects of class types that you have defined to or from a file.
EXERCISES
You can download the source code for the examples in the topic and the solutions to the following exer-
cises from www.wrox.com .
1. Write a program to read back the contents of the files written by the first exercise in the previous
chapter and output the proverb length that was read and the proverb itself for each of the proverbs.
2. Extend the ReadPrimes example that you produced in this chapter to optionally display the n th
prime, when n is entered from the keyboard.
3. Extend the ReadPrimes program further to output a given number of primes, starting at a given
number. For example, output 15 primes starting at the 30th. The existing capabilities should be re-
tained.
4. Write a program that outputs the contents of a file to the command line as groups of eight hexa-
decimal digits with five groups to a line, each group separated from the next by a space.
5. Write a program that allows either one or more names and addresses to be entered from the keyboard
and appended to a file, or the contents of the file to be read back and output to the command line.
6. Modify the previous example to store an index to the name and address file in a separate file. The
index file should contain each person's second name, plus the position where the corresponding name
and address can be found in the name and address file. Provide support for an optional command ar-
gument allowing a person's second name to be entered. When the command-line argument is present,
the program should then find the name and address and output it to the command line.
• WHAT YOU LEARNED IN THIS CHAPTER
TOPIC
CONCEPT
File Input/
Output
All file input and output is in terms of bytes. When you read bytes from a file, you must then interpret the
bytes as the types of data items that were written to the file.
Accessing
a File
You can obtain a FileChannel object connected to a file for reading, writing, or both by calling the static
newByteChannel() method in the Files class for the Path object that encapsulates the path to the file.
The method returns a reference of type SeekableByteChannel .
Reading
and Writ-
ing a File
The argument to the newByteChannel() method determines whether you open the file for reading, writ-
ing, or both. The argument can be one or more of the constants defined by the StandardOpenOption enu-
meration.
File Read
Operations
You call the read() method for a FileChannel object connected to a file to read() from the file.
Search WWH ::




Custom Search