Two Ways to Store Data in a File

  • Slides: 38
Download presentation
Two Ways to Store Data in a File u. Text format u. Binary format

Two Ways to Store Data in a File u. Text format u. Binary format

Text Format Information stored as a sequence of characters Characters are stored as their

Text Format Information stored as a sequence of characters Characters are stored as their ASCII equivalent - int value 12345 stored as ‘ 1’ ‘ 2’ ‘ 3’ ‘ 4’ ‘ 5’ 5 bytes 91 92 93 94 95 A text file is ‘readable’ by humans. Java classes ‘Reader’ and ‘Writer’ (and their subclasses) are for use with text files.

Text I/O u u In Java, characters are stored using UNICODE. Reader objects read

Text I/O u u In Java, characters are stored using UNICODE. Reader objects read characters in the current O. S. format, and convert them to UNICODE storage format. Writer objects convert the UNICODE stored data to character encoding used by the current O. S. Reader and Writer are abstract classes

Text Input READER class is an abstract class which is: extended by Input. Stream.

Text Input READER class is an abstract class which is: extended by Input. Stream. Reader which is extended by File. Reader Buffered. Reader class provides abstract methods which will be implemented specifically by all subclasses Input. Stream. Reader object reads bytes from an input stream and decodes them into characters, using the platform’s charset (ASCII for Windows). These characters are converted to UNICODE for storage. read() reads one character (number of bytes depends on charset) File. Reader object inherits Input. Stream. Reader capabilities, but the stream is a file. Buffered. Reader object is a wrapper for any Input. Stream. Reader (including File. Reader), and provides buffering (ie. handles multiple char reads and provides a string)

Text one char at a time u Create a Input. Stream. Reader object Constructor

Text one char at a time u Create a Input. Stream. Reader object Constructor takes an input stream, which may be keyboard, network connection, any input source Input. Stream. Reader in = new Input. Stream. Reader(System. in); u u u Input. Stream. Reader extends the Reader class, implementing input methods specifically for files Use its read method to read a single character o returns the next char as an int o or the integer -1 at end of input Test for -1 to determine if a char was read

Reading one char at a time…. Input. Stream. Reader reader = new Input. Stream.

Reading one char at a time…. Input. Stream. Reader reader = new Input. Stream. Reader(System. in); char c; //Java chars are UNICODE int next = reader. read() ; //byte read and if (next != -1) c = (char)next(); // process c next = reader. read() ; } //See demo test. ISReader. java

Reading one line at a time…. Input. Stream. Reader in = new Input. Stream.

Reading one line at a time…. Input. Stream. Reader in = new Input. Stream. Reader(System. in); //input is from keyboard Buffered. Reader bin = new Buffered. Reader(in); String val; val = bin. read. Line(); // get one string from keyboard while(val != null) { //while user does not enter CTRL Z System. out. println( val ); System. out. flush(); //output any lines waiting to be printed val = bin. read. Line(); } //See demo test. BISReader. java

Text one char at a time from a file u Create a File. Reader

Text one char at a time from a file u Create a File. Reader object u File. Reader extends the Reader class, implementing input methods specifically for files u Use its read method to read a single character o returns the next char as an int o or the integer -1 at end of input u Test for -1 to determine if a char was read u Close the file when done

Reading one char at a time from file…. File. Reader reader = new File.

Reading one char at a time from file…. File. Reader reader = new File. Reader("input. txt"); char c; //Java chars are UNICODE int next = reader. read() ; //byte read and if (next != -1){ c = (char)next(); next = reader. read(); reader. close(); // see test. File. Reader. java

Reading Text Line by Line Create a Buffered. Reader object (pass a File. Reader

Reading Text Line by Line Create a Buffered. Reader object (pass a File. Reader object to constructor) objects of type Buffered. Reader can group characters – ‘buffer’ them method read. Line() available, to provide file data 1 line at a time (the method handles reading the characters from the File. Reader for you) read. Line() returns the next line of file (as a String), or null if none exists

//Reads first line from file named input. txt // line is expected to contain

//Reads first line from file named input. txt // line is expected to contain a double value File. Reader reader = new File. Reader("input. txt"); Buffered. Reader in = new Buffered. Reader(reader); String input. Line = in. read. Line(); double x = Double. parse. Double(input. Line);

//Reads and all lines from file // and writes them to console import java.

//Reads and all lines from file // and writes them to console import java. io; public class demo{ public static void main(String[] args)throw IOException{ File. Reader reader = new File. Reader("input. txt"); Buffered. Reader in = new Buffered. Reader(reader); String line = in. read. Line(); While (line != null){ System. out. println(line); line = in. read. Line(); } in. close(); } }

Text Output WRITER class is an abstract class which is: extended by Output. Stream.

Text Output WRITER class is an abstract class which is: extended by Output. Stream. Writer which is extended by File. Writer Print. Writer class provides abstract methods which will be implemented specifically by all subclasses Output. Stream. Writer object writes bytes to an output stream and encodes them into characters, using the platform’s charset (ASCII for Windows). These characters are converted from stored UNICODE write(char) writes one character (number of bytes written depends on charset) Object is buffered, may be flushed File. Writer object is inherits Output. Stream. Writer capabilities, but the stream is a file Print. Writer object is a wrapper for any Output. Stream. Writer, and provides buffering (ie. handles multiple char writes and provides a string)

Write a Character to File. Writer class implements Writer methods specifically for files. File.

Write a Character to File. Writer class implements Writer methods specifically for files. File. Writer writer = new File. Writer("output. txt"); char c =‘a'; writer. write(c); writer. close();

Writing Strings to Text Files A Print. Writer object handles the ‘unbuffering’ of data

Writing Strings to Text Files A Print. Writer object handles the ‘unbuffering’ of data for output file writer Create Print. Writer object (pass File. Writer object to constructor) Print. Writer class provides ‘println’ method which accepts String and uses File. Writer to print one char at a time. File. Writer writer = new File. Writer(“output. txt”) Print. Writer out = new Print. Writer(writer);

//use Print. Writer object to output data to file output. txt File. Writer writer

//use Print. Writer object to output data to file output. txt File. Writer writer = new File. Writer(“output. txt”) Print. Writer out = new Print. Writer(writer); out. println(29. 95); out. println(new Rectangle(5, 10, 15, 25)); out. println("Hello, World!");

String. Tokenizer Class When reading a line of text, we get a single long

String. Tokenizer Class When reading a line of text, we get a single long string. Suppose our line of text looked something like: John|Doe|16|1998 In other words, the string contained know ‘delimiters’, and we wanted to access the ‘pieces’ between these delimiters. Java. util package provides a class to help here: String. Tokenizer Methods: String. Tokenizer(String theline, String delimiters) boolean has. More. Tokens() String next. Token() int count. Tokens() see file Count. THE. java

Binary Format More compact and efficient int 12345 stored using binary representation: 00000000 0010000

Binary Format More compact and efficient int 12345 stored using binary representation: 00000000 0010000 0011100 00 00 48 57 4 bytes Java abstract classes Input. Stream and Output. Stream (and their subclasses) provide methods for reading and writing these types of files

Binary File I/O u u In Java, an object from which we can read

Binary File I/O u u In Java, an object from which we can read a sequence of bytes is called an input stream. An object to which we can write a sequence of bytes is called an output stream. I/O streams have beginning, end, and are read sequentially. Input. Stream and Output. Stream are abstract classes.

Input. Stream class has an abstract method abstract int read() // reads and returns

Input. Stream class has an abstract method abstract int read() // reads and returns one byte An abstract method is an method which MUST be implemented by any extending class. The idea is that the extending class provides specifics… Output. Stream class has an abstract method abstract void write(int b); // writes one byte to output Java provides many stream classes which extend from Input. Stream and Output. Stream that let you work with data in the forms that you normally use……….

Byte Streams Input. Stream is extended by File. Input. Stream which is used for

Byte Streams Input. Stream is extended by File. Input. Stream which is used for byte based input from a file Output. Stream is extended by File. Output. Stream which is used for byte based output to a file Both of these classes implement read and write methods as specified in their abstract super classes. see file Byte. IO. java

Input Byte Streams Input. Stream is extended by Filter. Input. Stream is extended by

Input Byte Streams Input. Stream is extended by Filter. Input. Stream is extended by Data. Input. Stream Filter. Input. Stream acts as a ‘wrapper’ for an Input. Stream objects, which it uses as its basic source of data. Methods of Filter. Input. Stream objects simply pass requests to the Input. Stream objetct. Each subclass of Filter. Input. Stream transforms the data along the way, or provides some additional functionality. For example, Data. Input. Stream ‘wraps’ a Input. Stream object and assembles bytes read into numerical types. ** read. Int, read. Double, read. Boolean are just some of the methods available with a Data. Input. Stream object See file Data. Byte. IO. java

Input Byte Streams Input. Stream is extended by Filter. Input. Stream is extended by

Input Byte Streams Input. Stream is extended by Filter. Input. Stream is extended by Buffered. Input. Stream Another subclass of Filter. Input. Stream is Buffered. Input. Stream ‘wraps’ a Input. Stream object and provides ‘buffering’ for efficiency. Buffered. Input. Stream overloads ‘read’ so that in addition to one byte at a time, one byte array can be read. // buffered input Buffered. Input. Stream bin = new Buffered. Input. Stream(new Input. Stream(“file. txt”)); // add another layer so that Data. Input. Stream object will not do individual reads // for each byte, but use the buffered reads Data. Input. Stream dbin = new Data. Input. Stream(bin);

Output Byte Streams Filter. Output. Stream extends Output. Stream (Subclasses may be superclasses themselves)

Output Byte Streams Filter. Output. Stream extends Output. Stream (Subclasses may be superclasses themselves) Print. Stream extends Filter. Output. Stream acts as a ‘wrapper’ for an Output. Stream object, which it uses as its basic depository of data. Methods of Filter. Output. Stream simply pass requests to the Output. Stream objetct. Print. Stream ‘wraps’ a Output. Stream and provides an accurate display of data types to the output, in addition to buffering. Print. Stream also provides the overloaded println, which accepts String and byte[] parameters, as well as byte. System. out, is an object of type Print. Stream, which is provided by the System class in the java. lang input. System. out ‘wraps’ the Output. Stream object representins the console.

FILE OBJECTS provide methods which allow the creation, deletion, and other file manipulation/status methods…

FILE OBJECTS provide methods which allow the creation, deletion, and other file manipulation/status methods… File. Input. Stream and File. Reader constructors are overloaded to accept a File object. The file object will allow you to check the status of a file before you open it!! File f = new File(“in. txt”); if ( ! f. exists() ) System. out. println(“file does not exist”); else if ( ! F. can. Read() ) System. out. println(“file cannot be read”); else { File. Input. Stream in = new File. Input. Stream(f); Buffered. Input. Stream buf. In = new Buffered. Input. Stream(in); int bb = buf. In. read();

A JFile. Chooser Dialog

A JFile. Chooser Dialog

File Dialogs • Use JFile. Chooser to let a user supply a file name

File Dialogs • Use JFile. Chooser to let a user supply a file name through a file dialog • Construct a file chooser object • Call its show. Open. Dialog or show. Save. Dialog method (Specify null or the user interface component over which to pop up the dialog ) • If the user chooses a file: JFile. Chooser. APPROVE_OPTION is returned • If the user cancels the selection: JFile. Chooser. CANCEL_OPTION is returned • If a file is chosen, use Get. Selected. File method to obtain a File object describing the file

Code to Use a JFile. Chooser chooser new JFile. Chooser(); File. Reader in; if

Code to Use a JFile. Chooser chooser new JFile. Chooser(); File. Reader in; if (chooser. show. Open. Dialog(null) == JFile. Chooser. APPROVE_OPTION) { File selected. File = chooser. get. Selected. File(); in = new File. Reader(selected. File); } else in = null; // see file test. Dialog. java

Mark and Reset The abstract classes Input. Stream and Reader provide: void mark (int

Mark and Reset The abstract classes Input. Stream and Reader provide: void mark (int byte. Limit) * Marks the current position in this input stream. A subsequent call to the reset method repositions this stream at the last marked position so that subsequent reads re-read the same bytes. * byte. Limit is the number of bytes that can be read before this mark becomes invalid void reset() * repositions stream to position when mark was last called boolean mark. Supported () indicates if a stream supports these methods

int[] int. List; int. List = new int[100]; //this file contains one number 66

int[] int. List; int. List = new int[100]; //this file contains one number 66 File. Reader file = new File. Reader("number. txt"); Buffered. Reader ifile = new Buffered. Reader(file); // all array elements are initialized to 66 ifile. mark(5); for (int i = 0; i<100; i++){ String s. Val = ifile. read. Line(); ifile. reset(); int. List[i] = Integer. parse. Int(s. Val); }

Object Output Another byte (binary) I/O class which extends from Output. Stream is Object.

Object Output Another byte (binary) I/O class which extends from Output. Stream is Object. Output. Stream class can save entire objects to disk ! Objects that are written to an object stream must belong to a class that implements the Serializable interface. class Coin implements Serializable {. . . } ** Serializable interface has no methods.

Serializable u Objects that are written to an object stream must belong to a

Serializable u Objects that are written to an object stream must belong to a class that implements the Serializable interface. class Coin implements Serializable {. . . } ** Serializable interface has no methods.

Object. Output. Stream methods Stream does not just write objects ……. . write( )

Object. Output. Stream methods Stream does not just write objects ……. . write( ) - writes a byte write. Int(int) - writes a 32 bit int write. Double(double) - writes a 64 bit double write. Char(char) - writes a 16 bit char write. Object(Object) - writes the specified object to the output stream (if Serializable) close() - closes stream

Writing an Object to a File Output. Stream os = new File. Output. Stream("data.

Writing an Object to a File Output. Stream os = new File. Output. Stream("data. txt"); Object. Output. Stream out = new Object. Output. Stream(os); Array. List<Box> boxlist = new Array. List<Box> (); boxlist. add(new Box(5)); boxlist. add(new Box(17)); boxlist. add(new Box(20)); out. write. Object(boxlist); out. close();

Object Input u Another byte (binary) I/O class which extends from Input. Stream is

Object Input u Another byte (binary) I/O class which extends from Input. Stream is Object. Input. Stream class can read from a file, written by Object. Output. Stream (Data must by read with respect to datatype and order with which it was written)

Object. Input. Stream methods read( ) - reads a byte read. Int() - reads

Object. Input. Stream methods read( ) - reads a byte read. Int() - reads a 32 bit int read. Double() - reads a 64 bit double read. Char() - reads a 16 bit char read. Object( ) - reads the specified object to the input stream (if Serializable) close() - closes stream

Reading from File containing Objects public static void main(String[] args) throws IOException, Class. Not.

Reading from File containing Objects public static void main(String[] args) throws IOException, Class. Not. Found. Exception { Input. Stream is = new File. Input. Stream("data. txt"); Object. Input. Stream in = new Object. Input. Stream(is); Array. List<Box> boxlist = (Array. List<Box>) in. read. Object(); for (int i = 0; i< boxlist. size(); i++) System. out. println(boxlist. get(i)); in. close();

Random. vs. Sequential Access • Sequential access o A file is processed a byte

Random. vs. Sequential Access • Sequential access o A file is processed a byte at a time. • Random access o Allows access at arbitrary locations in the file