38
Computer Science [3] Computer Science [3] Java Programming II - Java Programming II - Laboratory Course Laboratory Course Lab 5: Lab 5: Introduction to Files & Streams Introduction to Files & Streams Input from Files , Class File Input from Files , Class File Serialization , JFileChooser Serialization , JFileChooser Faculty of Engineering & IT Software Engineering Department WWW. PALINFONET .COM Eng.Omar Al-Nahal

Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Embed Size (px)

Citation preview

Page 1: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Computer Science [3] Computer Science [3] Java Programming II - Java Programming II - Laboratory Laboratory

Course Course Lab 5:Lab 5:

Introduction to Files & StreamsIntroduction to Files & Streams

Input from Files , Class FileInput from Files , Class File

Serialization , JFileChooserSerialization , JFileChooser

Faculty of Engineering & ITSoftware Engineering Department

WWW.PALINFONET.COMWWW.PALINFONET.COM

Eng.Omar Al-Nahal

Eng.Omar Al-Nahal

Page 2: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

File I/OFile I/O

Page 3: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

IntroductionIntroduction

Storage of data in variables and arrays is temporaryStorage of data in variables and arrays is temporary Files used for long-term retention of large amounts of data, Files used for long-term retention of large amounts of data,

even after the programs that created the data terminateeven after the programs that created the data terminate Persistent data – exists beyond the duration of program Persistent data – exists beyond the duration of program

executionexecution Files stored on secondary storage devicesFiles stored on secondary storage devices Stream – ordered data that is read from or written to a fileStream – ordered data that is read from or written to a file

Page 4: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Files and StreamsFiles and Streams

File streamsFile streams• Byte-based streams – stores data in binary formatByte-based streams – stores data in binary format

– Binary files – created from byte-based streams, read by a Binary files – created from byte-based streams, read by a program that converts data to human-readable formatprogram that converts data to human-readable format

• Character-based streams – stores data as a sequence of charactersCharacter-based streams – stores data as a sequence of characters– Text files – created from character-based streams, can be read Text files – created from character-based streams, can be read

by text editorsby text editors Java opens file by creating an object and associating a stream with itJava opens file by creating an object and associating a stream with it Standard streams – each stream can be redirectedStandard streams – each stream can be redirected

• System.inSystem.in – standard input stream object, can be redirected with – standard input stream object, can be redirected with method method setInsetIn

• System.outSystem.out – standard output stream object, can be redirected – standard output stream object, can be redirected with method with method setOutsetOut

• System.errSystem.err – standard error stream object, can be redirected – standard error stream object, can be redirected with method with method setErrsetErr

Page 5: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

StreamsStreams

StreamStream: an object that either delivers data to its destination (screen, file, : an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.)etc.) or that takes data from a source (keyboard, file, etc.)

• it acts as a buffer between the data source and destinationit acts as a buffer between the data source and destination Input streamInput stream: a stream that provides input to a program: a stream that provides input to a program

• System.inSystem.in is an input stream is an input stream Output streamOutput stream: a stream that accepts output from a program: a stream that accepts output from a program

• System.outSystem.out is an output stream is an output stream A stream connects a program to an I/O objectA stream connects a program to an I/O object

• System.outSystem.out connects a program to the screen connects a program to the screen• System.inSystem.in connects a program to the keyboard connects a program to the keyboard

Page 6: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Binary Versus Text FilesBinary Versus Text Files

AllAll data and programs are ultimately just zeros and ones data and programs are ultimately just zeros and ones• each digit can have one of two values, hence each digit can have one of two values, hence binarybinary• bitbit is one binary digit is one binary digit• bytebyte is a group of eight bits is a group of eight bits

Text filesText files:: the bits represent printable characters the bits represent printable characters• one byte per character for ASCII, the most common codeone byte per character for ASCII, the most common code• for example, Java source files are text filesfor example, Java source files are text files• so is any file created with a "text editor"so is any file created with a "text editor"

Binary filesBinary files: the bits represent other types of encoded information, such : the bits represent other types of encoded information, such as executable instructions or numeric dataas executable instructions or numeric data• these files are easily read by the computer but not humansthese files are easily read by the computer but not humans• they are they are notnot "printable" files "printable" files

– actually, you actually, you cancan print them, but they will be unintelligible print them, but they will be unintelligible– "printable" means "easily readable by humans when printed""printable" means "easily readable by humans when printed"

Page 7: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Text Files vs. Binary FilesText Files vs. Binary Files

Number: 127 (decimal)Number: 127 (decimal)

• Text fileText file

– Three bytes: “1”, “2”, “7”Three bytes: “1”, “2”, “7”

– ASCII (decimal): 49, 50, 55ASCII (decimal): 49, 50, 55

– ASCII (octal): 61, 62, 67ASCII (octal): 61, 62, 67

– ASCII (binary): 00110001, 00110010, 00110111ASCII (binary): 00110001, 00110010, 00110111

• Binary fileBinary file: :

– One byte (One byte (bytebyte)):: 01111110 01111110

– Two bytes (Two bytes (shortshort): 00000000 01111110): 00000000 01111110

– Four bytes (Four bytes (intint): 00000000 00000000 00000000 01111110): 00000000 00000000 00000000 01111110

Page 8: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Text File I/OText File I/O

Important classes for text file Important classes for text file outputoutput (to the file) (to the file)• PrintWriterPrintWriter• FileOutputStream [FileOutputStream [oror FileWriter] FileWriter]

Important classes for text file Important classes for text file inputinput (from the file): (from the file):• BufferedReaderBufferedReader• FileReaderFileReader

FileOutputStreamFileOutputStream and and FileReaderFileReader take take file namesfile names as arguments. as arguments. PrintWriterPrintWriter and and BufferedReaderBufferedReader provide provide useful methodsuseful methods for easier for easier

writing and reading.writing and reading. Usually need a Usually need a combination of two classescombination of two classes To use these classes your program needs a line like the following:To use these classes your program needs a line like the following:

import java.io.*;import java.io.*;

Page 9: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

BufferingBuffering

Not bufferedNot buffered: each byte is read/written from/to disk as soon as possible: each byte is read/written from/to disk as soon as possible• ““little” delay for each byte little” delay for each byte • A disk operation per byte---higher overheadA disk operation per byte---higher overhead

BufferedBuffered: reading/writing in “chunks”: reading/writing in “chunks”• Some delay for some bytesSome delay for some bytes

– Assume 16-byte buffersAssume 16-byte buffers– Reading: access the first 4 bytes, need to wait for all 16 bytes are Reading: access the first 4 bytes, need to wait for all 16 bytes are

read from disk to memoryread from disk to memory– Writing: save the first 4 bytes, need to wait for all 16 bytes before Writing: save the first 4 bytes, need to wait for all 16 bytes before

writing from memory to diskwriting from memory to disk• A disk operation per a buffer of bytes---lower overheadA disk operation per a buffer of bytes---lower overhead

Page 10: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Text File OutputText File Output

To open a text file for output: connect a text file to a stream for writingTo open a text file for output: connect a text file to a stream for writing

PrintWriter outputStream =PrintWriter outputStream =new PrintWriter(new FileOutputStream("out.txt"));new PrintWriter(new FileOutputStream("out.txt"));

Similar to the long way:Similar to the long way:

FileOutputStream s = new FileOutputStream("out.txt");FileOutputStream s = new FileOutputStream("out.txt");

PrintWriter outputStream = new PrintWriter(s);PrintWriter outputStream = new PrintWriter(s);

Goal: create a Goal: create a PrintWriterPrintWriter object object

• which uses which uses FileOutputStreamFileOutputStream to open a text file to open a text file FileOutputStream “FileOutputStream “connects”connects” PrintWriter PrintWriter to a text file.to a text file.

Page 11: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Output File StreamsOutput File Streams

PrintWriter FileOutputStream

DiskMemory

smileyOutStream smiley.txt

PrintWriter smileyOutStream = new PrintWriter( new FileOutputStream(“smiley.txt”) );

Page 12: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Methods for Methods for PrintWriterPrintWriter

Similar to methods forSimilar to methods for System.out System.out printlnprintln

outputStream.println(count + " " + line);outputStream.println(count + " " + line);

printprint formatformat flushflush: write buffered output to disk: write buffered output to disk closeclose: close the : close the PrintWriterPrintWriter stream (and file) stream (and file)

Page 13: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

TextFileOutputDemo TextFileOutputDemo Part 1Part 1

public static void main(String[] args)public static void main(String[] args){{ PrintWriter outputStream = null;PrintWriter outputStream = null; trytry {{ outputStream =outputStream = new PrintWriter(new new PrintWriter(new

FileOutputStream("out.txt"));FileOutputStream("out.txt")); }} catch(FileNotFoundException e)catch(FileNotFoundException e) {{ System.out.println("Error opening the file out.txt. System.out.println("Error opening the file out.txt.

““ + e.getMessage());+ e.getMessage()); System.exit(0);System.exit(0); }}

A try-block is a block:outputStream would not be accessible to the rest of the method if it were declared inside the try-block

Creating a file can cause the FileNotFound-Exception if the new file cannot be made.

Page 14: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

System.out.println("Enter three lines of text:");System.out.println("Enter three lines of text:");

String line = null;String line = null;

int count;int count;

for (count = 1; count <= 3; count++)for (count = 1; count <= 3; count++)

{{

line = keyboard.nextLine();line = keyboard.nextLine();

outputStream.printlnoutputStream.println(count + " " + line);(count + " " + line);

}}

outputStream.close();outputStream.close();

System.out.printlnSystem.out.println("... written to out.txt.");("... written to out.txt.");

}}

The println method is used with two different streams: outputStream and System.out

Closing the file

Writing to the file

Part 2 Part 2 TextFileOutputDemoTextFileOutputDemo

Page 15: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Closing a FileClosing a File

An output file should be closed when you are done writing to it (and an An output file should be closed when you are done writing to it (and an input file should be closed when you are done reading from it).input file should be closed when you are done reading from it).

Use the Use the closeclose method of the class method of the class PrintWriter PrintWriter (BufferedReader (BufferedReader also has aalso has a close close methodmethod).).

For example, to close the file opened in the previous example:For example, to close the file opened in the previous example:outputStream.close();outputStream.close();

If a program ends normally it will close any files that are openIf a program ends normally it will close any files that are open ..

Page 16: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Input File StreamsInput File Streams

BufferedReader FileReader

DiskMemory

smileyInStream smiley.txt

BufferedReader smileyInStream = new BufferedReader( new FileReader(“smiley.txt”) );

Methods for BufferedReaderMethods for BufferedReader

readLine: read a line into a StringreadLine: read a line into a Stringno methods to read numbers directly, so read numbers as no methods to read numbers directly, so read numbers as Strings and then convert them (StringTokenizer later) Strings and then convert them (StringTokenizer later)read: read a char at a timeread: read a char at a timeclose: close BufferedReader streamclose: close BufferedReader stream

Page 17: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Exception Handling with File I/OException Handling with File I/O

Catching IOExceptionsCatching IOExceptions IOExceptionIOException is a predefined class is a predefined class File I/O might throw an File I/O might throw an IOExceptionIOException catch the exception in a catch block that at least prints an error message catch the exception in a catch block that at least prints an error message

and ends the programand ends the program FileNotFoundExceptionFileNotFoundException is derived from is derived from IOExceptionIOException

• therefor any catch block that catches therefor any catch block that catches IOExceptionIOExceptions also catches s also catches FileNotFoundExceptionFileNotFoundExceptionss

• put the more specific one first (the derived one) so it catches specifically put the more specific one first (the derived one) so it catches specifically file-not-found exceptionsfile-not-found exceptions

• then you will know that an I/O error is something other than file-not-then you will know that an I/O error is something other than file-not-foundfound

Page 18: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Example: Reading a File Name from the Keyboard

public static void main(String[] args) { String fileName = null; // outside try block, can be used in catch try { Scanner keyboard = new Scanner(System.in); System.out.println("Enter file name:"); fileName = keyboard.next(); BufferedReader inputStream = new BufferedReader(new FileReader(fileName)); String line = null; line = inputStream.readLine(); System.out.println("The first line in " + filename + " is:"); System.out.println(line); // . . . code for reading second line not shown here . . . inputStream.close(); } catch(FileNotFoundException e) { System.out.println("File " + filename + " not found."); } catch(IOException e) { System.out.println("Error reading from file " + fileName); } }

Chapter 10 18

reading a file name from the keyboard

closing the file

using the file name read from the keyboard

reading data from the file

Page 19: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Exception.getMessage()Exception.getMessage()

trytry{{ … …}}catch (FileNotFoundException e)catch (FileNotFoundException e){{ System.out.println(filename + “ not System.out.println(filename + “ not found”);found”);

System.out.println(“Exception: “ +System.out.println(“Exception: “ + e.getMessage());e.getMessage()); System.exit(-1);System.exit(-1);}}

Page 20: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Testing for End of File in a Text FileTesting for End of File in a Text File

When When readLinereadLine tries to read beyond the end of a text file it returns the tries to read beyond the end of a text file it returns the special value special value nullnull• so you can test for so you can test for nullnull to stop processing a text file to stop processing a text file

readread returns -1 when it tries to read beyond the end of a text file returns -1 when it tries to read beyond the end of a text file

• the the intint value of all ordinary characters is nonnegative value of all ordinary characters is nonnegative

Neither of these two methods (Neither of these two methods (readread and and readLinereadLine) will throw an ) will throw an EOFExceptionEOFException..

Page 21: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

int count = 0; String line = inputStream.readLine(); while (line != null) { count++; outputStream.println(count + " " + line); line = inputStream.readLine(); }

Chapter 9 21

Excerpt from TextEOFDemo

Example: Using Null toExample: Using Null toTest for End-of-File in a Text FileTest for End-of-File in a Text File

When using readLinetest for null

When using read test for -1

Page 22: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

File I/O exampleFile I/O example import java.io.*; import java.util.*; import java.text.*;

public class FileIONew { public static void main(String[] arg) { try { Scanner inFileStream = new Scanner(new File("in.txt"));

String name = null; int age = 0; float gpa = 0; while (inFileStream.hasNext()) { name = inFileStream.next(); age = inFileStream.nextInt(); gpa = inFileStream.nextFloat();

System.out.println(name + ' ' + age); } inFileStream.close(); } catch(FileNotFoundException e) { System.out.println(e.getMessage()); System.out.println("in.txt not found"); System.exit(-1); }

Page 23: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

catch(IOException e) { System.out.println(e.getMessage()); System.out.println("Error reading in.txt"); System.exit(-1); } try { PrintWriter outFileStream = new PrintWriter(new File("out.txt"));

outFileStream.println("Hello World"); outFileStream.println("Good Morning");

outFileStream.close(); } catch(FileNotFoundException e) { System.out.println(e.getMessage()); System.out.println("Can't open out.txt"); System.exit(-1); } catch(IOException e) { System.out.println(e.getMessage()); System.out.println("Error writing out.txt"); System.exit(-1); }

File outFile = new File("../FileIO/out.txt"); System.out.println(outFile.exists()); System.out.println(outFile.length()); System.out.println(outFile.getName()); System.out.println(outFile.getPath()); } }

Page 24: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

FileFile Class Class [java.io][java.io]

Acts like a wrapper class for file namesActs like a wrapper class for file names A file name like "A file name like "numbers.txtnumbers.txt" has only " has only StringString properties properties FileFile has some very useful methods has some very useful methods

• existsexists: tests if a file already exists: tests if a file already exists• canReadcanRead: tests if the OS will let you read a file: tests if the OS will let you read a file• canWritecanWrite: tests if the OS will let you write to a file: tests if the OS will let you write to a file• deletedelete: deletes the file, returns true if successful: deletes the file, returns true if successful• lengthlength: returns the number of bytes in the file: returns the number of bytes in the file• getNamegetName: returns file name, excluding the preceding path: returns file name, excluding the preceding path• getPathgetPath: returns the path name—the full name: returns the path name—the full name

File numFile = new File(“numbers.txt”);File numFile = new File(“numbers.txt”); if (numFile.exists())if (numFile.exists()) System.out.println(numfile.length());System.out.println(numfile.length());

Page 25: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

FileFile Objects and Filenames Objects and Filenames

FileInputStreamFileInputStream and and FileOutputStreamFileOutputStream have have constructors that take a constructors that take a FileFile argument as well as argument as well as constructors that take a constructors that take a StringString argument argument

PrintWriter smileyOutStream = new PrintWriter smileyOutStream = new PrintWriter(new PrintWriter(new FileOutputStream(“smiley.txt”));FileOutputStream(“smiley.txt”));

File smileyFile = new File(“smiley.txt”);File smileyFile = new File(“smiley.txt”);

if (smileyFile.canWrite())if (smileyFile.canWrite())

PrintWriter smileyOutStream = new PrintWriter smileyOutStream = new PrintWriter(new PrintWriter(new FileOutputStream(smileyFile));FileOutputStream(smileyFile));

Page 26: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Reading in Reading in intint’s’s

Scanner inFile = new Scanner(new File(“in.txt"));Scanner inFile = new Scanner(new File(“in.txt"));

int number;int number;

while (inFile.hasInt())while (inFile.hasInt())

{{

number = inFile.nextInt();number = inFile.nextInt();

// …// …

}}

Reading in lines of charactersReading in lines of charactersScanner inFile = new Scanner(new File(“in.txt"));Scanner inFile = new Scanner(new File(“in.txt"));String line;String line;while (inFile.hasNextLine())while (inFile.hasNextLine()) {{

line = inFile.nextLine();line = inFile.nextLine(); // … }// … }

Page 27: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Multiple types on one lineMultiple types on one line

// Name, id, balance // Name, id, balance Scanner inFile = new Scanner(new File(“in.txt"));Scanner inFile = new Scanner(new File(“in.txt"));while (inFile.hasNext())while (inFile.hasNext()) {{ name = inFile.next();name = inFile.next(); id = inFile.nextInt();id = inFile.nextInt(); balance = inFile.nextFloat();balance = inFile.nextFloat(); // … new Account(name, id, balance);// … new Account(name, id, balance); }}----------------------------------------String line;String line;while (inFile.hasNextLine())while (inFile.hasNextLine()) {{

line = inFile.nextLine();line = inFile.nextLine(); Scanner parseLine = new Scanner(line) // Scanner again!Scanner parseLine = new Scanner(line) // Scanner again!

name = parseLine.next();name = parseLine.next(); id = parseLine.nextInt();id = parseLine.nextInt(); balance = parseLine.nextFloat();balance = parseLine.nextFloat(); // … new Account(name, id, balance);// … new Account(name, id, balance); }}

Page 28: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Multiple types on one lineMultiple types on one line

// Name, id, balance // Name, id, balance Scanner inFile = new Scanner(new File(“in.txt"));Scanner inFile = new Scanner(new File(“in.txt"));String line;String line;while (inFile.hasNextLine())while (inFile.hasNextLine()) {{

line = inFile.nextLine();line = inFile.nextLine(); Account account = new Account(line);Account account = new Account(line);

}}----------------------------------------public Account(String line) // constructorpublic Account(String line) // constructor{{ Scanner accountLine = new Scanner(line);Scanner accountLine = new Scanner(line); _name = accountLine.next();_name = accountLine.next(); _id = accountLine.nextInt();_id = accountLine.nextInt(); _balance = accountLine.nextFloat();_balance = accountLine.nextFloat();}}

Page 29: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Binary I/O of Class ObjectsBinary I/O of Class Objects

read and write class objects in binary fileread and write class objects in binary file

class must be class must be serializableserializable• import java.io.*import java.io.*• implement implement SerializableSerializable interface interface

• add add implements Serializableimplements Serializable to heading of class definition to heading of class definition

methods used:methods used:

to write object to file:writeObject method in ObjectOutputStream

to read object from file: readObject method in ObjectInputStream

public class Species implements Serializable

Page 30: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

The The SerializableSerializable Interface Interface

Java assigns a serial number to each object written out.Java assigns a serial number to each object written out.

• If the same object is written out more than once, after the first write If the same object is written out more than once, after the first write only the serial number will be written.only the serial number will be written.

• When an object is read in more than once, then there will be more When an object is read in more than once, then there will be more than one reference to the same object.than one reference to the same object.

If a serializable class has class instance variables then they should also be If a serializable class has class instance variables then they should also be serializable.serializable.

Why aren't all classes made serializable?Why aren't all classes made serializable?

• security issues: serial number system can make it easier for security issues: serial number system can make it easier for programmers to get access to object dataprogrammers to get access to object data

• doesn't make sense in all cases, e.g., system-dependent datadoesn't make sense in all cases, e.g., system-dependent data

Page 31: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

SerializationSerialization

You can also read and write You can also read and write objectsobjects to files to files Object I/O goes by the awkward name of Object I/O goes by the awkward name of serializationserialization Serialization in other languages can be Serialization in other languages can be veryvery difficult, difficult,

because objects may contain references to other objectsbecause objects may contain references to other objects Java makes serialization (almost) easyJava makes serialization (almost) easy

Conditions for serializabilityConditions for serializability

If an object is to be serialized:If an object is to be serialized:The class must be declared as publicThe class must be declared as publicThe class must implement The class must implement SerializableSerializableThe class must have a no-argument constructorThe class must have a no-argument constructorAll fields of the class must be serializable: either primitive All fields of the class must be serializable: either primitive types or serializable objectstypes or serializable objects

Page 32: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Random Access FilesRandom Access Files

Random access files are files in which records can be accessed in any Random access files are files in which records can be accessed in any orderorder

The RandomAccessFile class contains the same read(), write() The RandomAccessFile class contains the same read(), write() and close() methods as Input and OutputStreamand close() methods as Input and OutputStreamAlso contains seek() that lets you select a beginning position Also contains seek() that lets you select a beginning position within the file before reading or writing datawithin the file before reading or writing data

RandomAccessFiles classRandomAccessFiles class

Page 33: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

File PointerFile Pointer

RandomAccessFile supportsRandomAccessFile supports file pointerfile pointer which indicates the which indicates the current location in the file. current location in the file.

When the file is first created, the file pointer is set to 0, When the file is first created, the file pointer is set to 0, indicating the beginning of the file. Calls to the read and indicating the beginning of the file. Calls to the read and write methods adjust the file pointer by the number of write methods adjust the file pointer by the number of bytes read or written. bytes read or written.

Creates a random access file streamCreates a random access file stream to read from, and optionally to read from, and optionally to write to, a file with the specified name.to write to, a file with the specified name.The mode should be either “r” or “rw” No using “w”The mode should be either “r” or “rw” No using “w”

Page 34: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

RandomAccessFileRandomAccessFile

To move the file pointer to a specific byte To move the file pointer to a specific byte f.seek(n);f.seek(n);

To get current position of the file pointer.To get current position of the file pointer.

long n = f.getFilePointer();long n = f.getFilePointer(); To find the number of bytes in a fileTo find the number of bytes in a file

long filelength = f.length();long filelength = f.length();

Page 35: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

About About JFileChooserJFileChooserss

The The JFileChooserJFileChooser class displays a window from class displays a window from which the user can select a filewhich the user can select a file

The dialog window is The dialog window is modalmodal--the application cannot --the application cannot continue until it is closedcontinue until it is closed

Applets cannot use a Applets cannot use a JFileChooserJFileChooser, because applets , because applets cannot access filescannot access files

Typical Typical JFileChooserJFileChooser window window

Page 36: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

JFileChooserJFileChooser constructors constructors

JFileChooser()JFileChooser()• Creates a Creates a JFileChooserJFileChooser starting from the user’s starting from the user’s

directorydirectory

JFileChooser(File JFileChooser(File currentDirectorycurrentDirectory))• Constructs a Constructs a JFileChooserJFileChooser using the given using the given FileFile as the as the

pathpath

JFileChooser(String JFileChooser(String currentDirectoryPathcurrentDirectoryPath))• Constructs a Constructs a JFileChooser JFileChooser using the given pathusing the given path

Page 37: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Useful Useful JFileChooserJFileChooser methods I methods I int showOpenDialog(Component enclosingJFrame);

• Asks for a file to read; returns a flag. int showSaveDialog(Component enclosingJFrame);

• Asks where to save a file; returns a flag. Returned flag value may be:

- JFileChooser.APPROVE_OPTION - JFileChooser.CANCEL_OPTION• JFileChooser.ERROR_OPTION

Useful Useful JFileChooserJFileChooser methods II methods IIFile getSelectedFile()

showOpenDialog and showSaveDialog return a flag telling what happened, but don’t return the selected fileAfter we return from one of these methods, we have to ask the JFileChooser what file was selectedIf we are saving a file, the File may not actually exist yet—that’s OK, we still have a File object we can use

Page 38: Computer Science [3] Java Programming II - Laboratory Course Lab 5: Introduction to Files & Streams Input from Files, Class File Serialization, JFileChooser

Using a Using a FileFile

Assuming that we have successfully selected a File:

• File file = chooser.getSelectedFile();if (file != null) { String fileName = file.getCanonicalPath(); FileReader fileReader = new FileReader(fileName); BufferedReader reader = new BufferedReader(fileReader); }

• File file = chooser.getSelectedFile();if (file != null) { String fileName = file.getCanonicalPath(); FileOutputStream stream = new FileOutputStream(fileName); writer = new PrintWriter(stream, true);}