BOOK NOTES CHAPTER 16 FILES AND STREAMS 16.1 READING AND WRITING TEXT FILES - text file - created w/ a simple text editor - e.g. Notepad .txt files, Java source, HTML files - read text - construct a java.io.FileReader object w/ name of input file (can throw java.io.FileNotFoundException if file with that name doesn't exist) FileReader reader = new FileReader("input.txt"); - use FileReader to construct a Scanner object Scanner in = new Scanner(reader); - use Scanner methods to read text from input file - write text - construct a java.io.PrintWriter object with the given file name PrintWriter out = new PrintWriter("output.txt"); - if file already exists, old contents are deleted before new data is added - if file doesn't exist, empty file is created - use print and println methods to write data - convert numbers to their decimal string representations - use the toString method to convert objects to strings - must close PrintWriter when done; if program exits without closing, output may not make it to file out.close(); - backslashes in file names - backslash is the escape character in strings - when creating a string in code, use the character '\\' to represent a literal backslash AT 16.1 - java.io.File class - object to represent a file - constructor File(String pathname) File inputFile = new File("input.txt"); - contains methods to delete and rename a file - does not have to exist - test for existance boolean File::exists() - pass File object to output stream or writer to create - cannot use directly for reading or writing - read a File object - use the File to construct a FileReader FileReader(File file) FileReader in = new FileReader(inputFile); AT 16.2 COMMAND LINE ARGUMENTS - invoking program from command line: starting program by typing its name in a terminal/shell window - command line arguments - specify additonal input to program on invocation - type each one, whitespace delimited, after the program name - placed in the args parameter of the main method - program determines how to interpret input - customary - strings starting with a hyphen as options - other strings as file names - GUI better for casual and infrequent user - GUI hard to automate: can use shell scripts to automate command line input 16.2 TEXT AND BINARY FORMATS ***ELIMINATED*** - ways to store data - text format - data items represented as sequence of characters - human-readable - requires Reader and Writer classes to process IO - more convenient for people - create with text editor - verify by reading - read from disk file FileReader reader = new FileReader("input.txt"); - write data to disk FileWriter writer = new FileWriter("output.txt"); - binary format - data items represented in bytes - 8 bits - 256 possible values - usually represented as 2 hexadecimal digits - process IO with InputStream and OutputStream classes (and subclasses) - more compact and efficient - read from disk FileInputStream inputStream = new FileInputStream("input.bin"); - write data to disk FileOutputStream outputStream = new FileOutputStream("output.bin"); - Reader class - read method - read a single character at a time - FileReader overrides to obtain characters from a disk file - actually returns an int: signal - character has been read: returns integer between 0 and 65, 535 - end of input has been reached: returns -1 - test return value, and if not -1, cast to a char Reader reader = ...; int next = reader.read(); char c; if (next != 1) c = (char) next; - InputStream class - read method - read a single byte - returns an int - byte that was input: 0-255 - end of input stream: -1 - test, and if not -1, convert to byte InputStream in = ...; int next = in.read(); byte b; if (next != -1) b = (byte) next; - Writer class write method writes single char - FileOutputStream class write method writes single byte - read and write are only io provided by file io classes - Java stream package - each class has a very focused responsibility - must combine with other classes that know how to interpret bytes as Java primitives/objects CE 16.2 NEGATIVE BYTE VALUES - cast int to byte: lowest byte of int is taken - bytes are signed - first bit determines if positive or negative - 0 is positive, 1 is negative - means when cast int to byte, sign might not stay the same - if convert back to int, get byte value (not necessarily the same as original int) 16.3 AN ENCRYPTION PROGRAM - encryption: scrambles a file so it is unreadable except to those who know the decryption method and secret keyword - Caeser Cipher - shift letters by some amount between 1 and 25 - decrypt by shifting by -(key) 16.4 RANDOM ACCESS *** ELIMINATED *** - sequential access - starting at the beginning,read all contents of file through the end - can be inefficient - random access - read and modify any byte at any location in any order - only supported by disk files - file pointer - one per disk file - specifies where to access the file - reads occur where it points - if at end and write, adds data - if in middle and write, overwrites data - java.io.RandomAccessFile - access a file - move a file pointer - RandomAccessFile(String name, String mode) - mode - "r": reading only - "rw": reading and writing - void seek(long pos) - move file pointer to byte n - counted from beginning of file - long getFilePointer() - get current position of file pointer - counted in bytes from beginning of file - pay special attention to data formatting - give each value a fixed size that is sufficiently large - since updates are overwrites - easily skip to a specific record by multiplying by size of record - easier to store numbers in binary format than as text - int RandomAccessFile::readInt(): read 4B starting at file pointer - void RandomAccessFile::writeInt(int v): overwrite 4B starting at file pointer - double RandomAccessFile::readDouble(): read 8B from fp - void RandomAccessFile::writeDouble(double v): overwrite 8B at fp 16.5 OBJECT STREAMS *** OPTIONAL ***