Files and Streams Presented By S Aravind Goals

Files and Streams Presented By S. Aravind

Goals To be able to read and write text files n To become familiar with the concepts of text and binary formats n To learn about encryption n To understand when to use sequential and random file access n To be able to read and write objects using serialization n

keyboard standard input stream CPU standard output stream monitor terminal console What does information travel across? Streams MEM HDD

keyboard standard input stream CPU monitor terminal console standard output stream What does information travel across? Streams file input stream LOAD READ MEM HDD files file output stream SAVE WRITE

Reading and Writing Text Files n Text files – files containing simple text n n Simplest way to learn it so extend our use of Scanner n n Created with editors such as notepad, html, etc. Associate with files instead of System. in All input classes, except Scanner, are in java. io n import java. io. *;

Review: Scanner We've seen Scanner before n The constructor takes an object of type java. io. Input. Stream – stores information about the connection between an input device and the computer or program n n n Example: System. in Recall – only associate one instance of Scanner with System. in in your program n Otherwise, get bugs

Numerical Input n 2 ways (we’ve learned one, seen the other) n n Use int as example, similar for double First way: n Use next. Int() int number = scanner. next. Int(); n Second way: n Use next. Line(), Integer. parse. Int() String input = scanner. next. Line(); int number = Integer. parse. Int(input);

Numerical Input n Exceptions n next. Int() throws Input. Mismatch. Exception parse. Int() throws Number. Format. Exception Optimal use n next. Int() when there is multiple information on one line n next. Line() + parse. Int() when one number per line

Reading Files n The same applies for both console input and file input n We can use a different version of a Scanner that takes a File instead of System. in n Everything works the same!

Reading Files n To read from a disk file, construct a File. Reader n Then, use the File. Reader to construct a Scanner object File. Reader rdr = new. File. Reader("input. txt"); Scanner fin = new Scanner(rdr);

Reading Files n You can use File instead of File. Reader n Has an exists() method we can call to avoid File. Not. Found. Exception File file = new File ("input. txt"); Scanner fin; if(file. exists()){ fin = new Scanner(file); } else { //ask for another file }

Reading Files n Once we have a Scanner, we can use methods we already know: n n next, next. Line, next. Int, etc. Reads the information from the file instead of console

File Class n java. io. File n associated with an actual file on hard drive n used to check file's status n Constructors n n n File(<full path>) File(<path>, <filename>) Methods n n n exists() can. Read(), can. Write() is. File(), is. Directory()

File Class n java. io. File. Reader n Associated with File object n Translates data bytes from File object into a stream of characters (much like Input. Stream vs. Input. Stream. Reader) n Constructors n n File. Reader( <File object> ); Methods read(), read. Line() n close() n

Writing to a File n We will use a Print. Writer object to write to a file What if file already exists? Empty file n Doesn’t exist? Create empty file with that name n n How do we use a Print. Writer object? n Have we already seen one?

Writing to a File n The out field of the System class is a Print. Writer object associated with the console n We will associate our Print. Writer with a file now Print. Writer fout = new Print. Writer("output. txt"); fout. println(29. 95); fout. println(new Rectangle(5, 10, 15, 25)); fout. println("Hello, World!"); n This will print the exact same information as with System. out (except to a file “output. txt”)!

Closing a File n Only main difference is that we have to close the file stream when we are done writing n If we do not, not all output will written n At the end of output, call close() fout. close();

Closing a File n Why? When you call print() and/or println(), the output is actually written to a buffer. When you close or flush the output, the buffer is written to the file n The slowest part of the computer is hard drive operations – much more efficient to write once instead of writing repeated times n

File Locations When determining a file name, the default is to place in the same directory as your. class files n If we want to define other place, use an absolute path (e. g. c: My Documents) n in = new File. Reader(“c: \homework\input. dat”); n Why \ ?

Sample Program n Two things to notice: Have to import from java. io n I/O requires us to catch checked exceptions n n java. io. IOException

Java Input Review CONSOLE: Scanner stdin = new Scanner( System. in ); FILE: Scanner in. File = new Scanner( new File. Reader(src. File. Name ));

Java Output Review n CONSOLE: System. out. print("To the screen"); n FILE: Print. Writer fout = new Print. Writer(new File("output. txt"); fout. print("To a file");

import java. io. File. Reader; java. io. IOException; java. io. Print. Writer; java. util. Scanner; public class Line. Numberer{ public static void main(String[] args){ Scanner console = new Scanner(System. in); System. out. print("Input file: "); String in. File = console. next(); System. out. print("Output file: "); String out. File = console. next(); try{ File. Reader reader = new File. Reader(in. File); Scanner in = new Scanner(reader);

Print. Writer out = new Print. Writer(output. File. Name); int line. Number = 1; while (in. has. Next. Line()){ String line = in. next. Line(); out. println("/* " + line. Number + " */ " + line); line. Number++; } out. close(); } catch (IOException exception){ System. out. println("Error processing file: " + exception); } } }

An Encryption Program n Demonstration: Use encryption to show file techniques n File encryption To scramble a file so that it is readable only to those who know the encryption method and secret keyword n (Big area of CS in terms of commercial applications – biometrics, 128 -bit encryption breaking, etc. ) n

Modifications of Output n Two constraints so far: Files are overwritten n Output is buffered and not written immediately n n We have options to get around this

File Class n java. io. File. Writer Associated with File object n Connects an output stream to write bytes of info n n Constructors n n File. Writer( <filename>, <boolean> ); n true to append data, false to overwrite all of file This will overwrite an existing file n To avoid, create File object and see if exists() is true

Java File Output n Print. Writer n composed from several objects Print. Writer out = new Print. Writer( new File. Writer( dst. File. Name, false n n ), true ); requires throws File. Not. Found. Exception, which is a sub class of IOException Methods n print(), println(): buffers data to write n flush(): sends buffered output to destination n close(): flushes and closes stream

Java File Output // With append to an existing file Print. Writer out. File 1 = new Print. Writer( new File. Writer(dst. File. Name, true), false); // With autoflush on println Print. Writer out. File 2 = new Print. Writer( new File. Writer(dst. File. Name, false), true); out. File 1. println( “appended w/out flush” ); out. File 2. println( “overwrite with flush” );

To flush or not to flush n Advantage to flush: n n Safer – guaranteed that all of our data will write to the file Disadvantage n Less efficient – writing to file takes up time, more efficient to flush once (on close)

Caeser Cipher n Encryption key – the function to change the value n Simple key – shift each letter over by 1 to 25 characters n n If key = 3, A D B E etc. Decryption = reversing the encryption n Here we just subtract the key value


Binary File Encryption int next = in. read(); if (next == -1) done = true; else { byte b = (byte) next; //call the method to encrypt the byte c = encrypt(b); out. write(c); }




Object Streams n Last example read Bank. Account field individually n n Easier way to deal with whole object Object. Output. Stream class can save a entire Object. Output. Stream class can read objects to disk n back in from disk n Objects are saved in binary format; hence, you use streams and not writers

Write out an object n The object output stream saves all instance variables Bank. Account b =. . . ; Object. Output. Stream out = new Object. Output. Stream( new File. Output. Stream("bank. dat")); out. write. Object(b);

Read in an object n n read. Object returns an Object reference Need to remember the types of the objects that you saved and use a cast Object. Input. Stream in = new Object. Input. Stream( new File. Input. Stream("bank. dat")); Bank. Account b = (Bank. Account) in. read. Object();

Exceptions n read. Object method can Class. Not. Found. Exception throw a n It is a checked exception n You must catch or declare it

Writing an Array n Usually want to write out a collection of objects: Bank. Account[] arr = new Bank. Account[size]; // Now add size Bank. Account objects into arr out. write. Object(arr);

Reading an Array n To read a set of objects into an array Bank. Account[] ary = (Bank. Account[]) in. read. Object();

Object Streams n Very powerful features n n Especially considering how little we have to do The Bank. Account class as is actually will not work with the stream n Must implement Serializable interface in order for the formatting to work

Object Streams class Bank. Account implements Serializable {. . . } IMPORTANT: Serializable interface has no methods. n No effort required n

Serialization n Serialization: process of saving objects to a stream Each object is assigned a serial number on the stream n If the same object is saved twice, only serial number is written out the second time n When reading, duplicate serial numbers are restored as references to the same object n

Serialization n Why isn’t everything serializable? Security reasons – may not want contents of objects printed out to disk, then anyone can print out internal structure and analyze it n Example: Don’t want SSN ever being accessed n Could also have temporary variables that are useless once the program is done running n

Tokenizing n Often several text values are in a single line in a file to be compact “ 25 38 36 34 29 60 59” n The line must be broken into parts (i. e. tokens) “ 25” “ 38” “ 36” n tokens then can be parsed as needed “ 25” can be turned into the integer 25

Tokenizing n Inputting each value on a new line makes the file very long n May want a file of customer info – name, age, phone number all on one line n File usually separate each piece of info with a delimiter – any special character designating a new piece of data (space in previous example)

Tokenizing in Java n use a String. Tokenizer object default delimiters are: space, tab, newline, return n requires: import java. util. * n n Constructors n n n String. Tokenizer(String line)//default dlms String. Tokenizer(String ln, String dlms) Methods n n n has. More. Tokens() next. Token() count. Tokens()

String. Tokenizing in Java Scanner stdin = new… System. out. print( "Enter a line with comma seperated integers(no space): " ); String input = stdin. next. Line(); String. Tokenizer st; String delims = ", "; st = new String. Tokenizer( input, delims ); while ( st. has. More. Tokens() ) { int n = Integer. parse. Int(st. next. Token()); System. out. println(n); }

File grade. File = new File(“scores. txt”); if(grade. File. exists()){ Scanner in. File = new Scanner(grade. File); String line = in. File. next. Line(); while(line != null){ String. Tokenizer st = new String. Tokenizer(line, ": "); System. out. print(" Name: " + st. next. Token()); int num = 0; double sum = 0; while ( st. has. More. Tokens() ) { num++; sum += Integer. parse. Int(st. next. Token()); } System. our. println(" average = "+ sum/num); line = in. File. next. Line();

} in. File. close(); } If you call next. Token() and there are no more tokens, No. Such. Element. Exception is thrown

Tokenizing n Scanner tokenizes already… Scanner in = new Scanner(…); while(in. has. Next()) { String str = in. next(); … }
- Slides: 53