260 likes | 419 Views
Streams and File I/O. October 23, 2013. 10.1 AN OVERVIEW OF STREAMS AND FILE I/O . A stream is a flow of data. The data might be characters, numbers, or bytes consisting of binary digits. If the data flows into your program, the stream is called an input stream.
E N D
Streams and File I/O October 23, 2013
10.1 AN OVERVIEW OF STREAMS AND FILE I/O • A stream is a flow of data. • The data might be characters, numbers, or bytes consisting of binary digits. • If the data flows into your program, the stream is called an input stream. • If the data flows out of your program, the stream is called an output stream.
Stream • A stream is an object that either • Delivers data from program to a destination, such as a file or the screen • Takes data from a source, such as a file or the keyboard, and delivers the data to program
Text Files and Binary Files • All the data in any file is stored as bits – that is a long sequence of 0s and 1s. • Text file – bits are interpreted as sequence of characters • Binary file – all other file • Java program can read both text and binary files
10.2 TEXT-FILE I/O • Creating/Writing to a Text File • Appending to a Text File • Reading from a Text File
Creating/Writing to a Text File • Stream variable – reference to stream • Class PrintWriter in java.io connects a file to an output stream • Overwrites file contents
Appending to a Text File • Append – write at the end of the file • Old content of the file will remain • PrintWriter does not have appropriate constructor • We need class FileOutputStream from java.io
Reading from a Text File • Scanner class • Constructor of Scanner does not take a String argument as filename • Constructor of Scanner accepts an instance of File class • File has a constructor to take a String argument as filename
10.3 TECHNIQUES FOR ANY FILE:The Class File • The class File provides a way to represent file names in a general way. • A string “treasure.txt” is just a string to Java • Class File create an object which Java recognize as a name of a file.
Using Path Names (1/3) • When file and the program are in the same directory – we specify only filename • If they are in different location – we have to specify path name instead of filename • Full path name – complete path name starting from the root directory • Relative path name – path to the file starting from the current working directory
Using Path Names (3/3) • Java program accepts • Unix format path name in Unix, Windows • Windows format path name in Unix, Windows