ptg7068951
286 HOUR 20: Reading and Writing Files
When you read an input stream, it begins with the first byte in the stream,
such as the first byte in a file. You can skip some bytes in a stream by calling
itsskip()method with one argument: an intrepresenting the number of
bytes to skip. The following statement skips the next 1024 bytes in a stream
named scanData:
scanData.skip(1024);
If you want to read more than one byte at a time, do the following:
. Create a byte array that is exactly the size of the number of bytes you
want to read.
. Call the stream’s read()method with that array as an argument. The
array is filled with bytes read from the stream.
You create an application that reads ID3 data from an MP3 audio file.
Because MP3 is such a popular format for music files, 128 bytes are often
added to the end of an ID3 file to hold information about the song, such as
the title, artist, and album.
The ID3Readerapplication reads an MP3 file using a file input stream, skip-
ping everything but the last 128 bytes. The remaining bytes are examined to
see if they contain ID3 data. If they do, the first three bytes are the numbers
84, 65, and 71.
Create a new empty Java file called ID3Readerand fill it with the text from
Listing 20.1.
LISTING 20.1 The Full Text of ID3Reader.java
1: importjava.io.*;
2:
3: public classID3Reader {
4: public static voidmain(String[] arguments) {
5: try {
6: File song = new File(arguments[0]);
7: FileInputStream file = new FileInputStream(song);
8: int size = (int) song.length();
9: file.skip(size - 128);
10: byte[] last128 = new byte[128];
11: file.read(last128);
12: String id3 = new String(last128);
13: String tag = id3.substring(0, 3);
14: if (tag.equals(“TAG”)) {
15: System.out.println(“Title: “+ id3.substring(3, 32));
16: System.out.println(“Artist: “+ id3.substring(33, 62));
17: System.out.println(“Album: “+ id3.substring(63, 91));
NOTE
On the ASCII character set,
which is included in the
Unicode Standard character set
supported by Java,those three
numbers represent the capital
letters “T,” “A,” and “G,” respec-
tively.