CHAPTER 8 ■ WRITING AND READING FILES
// Close the output stream
hamletOutputStream.close();
System.out.println("New contents of hamlet.txt written");
} catch (FileNotFoundException fnfe) {
System.out.println("Couldn't find a file called " + fileName);
} catch (IOException ioe) {
System.out.println("Couldn't write to a file called " + fileName);
}
}
private static void reverseByteArray(byte[] inBytes) {
int inLength = inBytes.length;
for (int i = 0; i < inLength >> 1; i++) {
byte temp = inBytes[i];
inBytes[i] = inBytes[inLength - i - 1];
inBytes[inLength - i - 1] = temp;
}
}
}
And now we have Hamlet going forwards and backwards in Listing 8-18.
Listing 8-18. Original and reversed content
To sleep: perchance to dream: ay, there's the rub;
For in that sleep of death what dreams may come
When we have shuffled off this mortal coil,
Must give us pause: there's the respect
That makes calamity of so long life
efil gnol os fo ytimalac sekam tahT
tcepser eht s'ereht :esuap su evig tsuM
,lioc latrom siht ffo delffuhs evah ew nehW
emoc yam smaerd tahw htaed fo peels taht ni roF
;bur eht s'ereht ,ya :maerd ot ecnahcrep :peels oT
Summary
Software developers often need to work with files, and Java has a rich set of classes that let us do so. As
we saw, we use the File class to work with files and directories, and we use streams (FileInputStream
objects and FileOutputStream objects) to read and write files. We learned a number of things about File,
FileInputStream, and FileOutputStream objects:
- A File object can represent a directory structure defined by a path.
- A File object is not a file or directory. It is an object that represents a file or
directory. - The file or directory represented by a File object does not necessarily exist.
- A failed attempt to create directories can leave unwanted directories, so we need
to clean up after a failed directory creation operation.