slide1 n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Files and Streams PowerPoint Presentation
Download Presentation
Files and Streams

Loading in 2 Seconds...

play fullscreen
1 / 63

Files and Streams - PowerPoint PPT Presentation


  • 80 Views
  • Uploaded on

Files and Streams. OBJECTIVES. In this chapter you will learn: Write bytes to a file and read them back from the file, using FileOutputStream and FileInputStream. Write values of primitive data types to a file and read them back from the file, using DataOutputStream and DataInputStream.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Files and Streams' - sylvie


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
objectives
OBJECTIVES

In this chapter you will learn:

  • Write bytes to a file and read them back from the file, using FileOutputStream and FileInputStream.
  • Write values of primitive data types to a file and read them back from the file, using DataOutputStream and DataInputStream.
  • Write text data to a file and read them back from the file, using PrintWriterand BufferedReader.
  • Read a text file using Scanner
  • Write objects to a file and read them back from the file, using ObjectOutputStream and ObjectInputStream
introduction
Introduction
  • Storage of data in variables and arrays is temporary
  • Files used for long-term retention of large amounts of data, even after the programs that created the data terminate
  • Persistent data – exists beyond the duration of program execution
  • Files stored on secondary storage devices
  • Stream – ordered data that is read from or written to a file
data hierarchy
Data Hierarchy
  • Computers process all data items as combinations of zeros and ones
  • Bit – smallest data item on a computer, can have values 0 or 1
  • Byte – 8 bits
  • Characters – larger data item
    • Consists of decimal digits, letters and special symbols
    • Character set – set of all characters used to write programs and represent data items
      • Unicode – characters composed of two bytes
data hierarchy1
Data Hierarchy
  • Fields – a group of characters or bytes that conveys meaning
  • Record – a group of related fields
  • File – a group of related records
slide7

There are two general types of files you need to learn about:

textfiles and binaryfiles…

•A text, or character-based, file stores information using unicode character representations. Text files can be viewed with a standard editor or word processing program but cannot be manipulated arithmetically without requiring special conversion routines.

•A binary file stores numerical values using the internal numeric binary format specified by java. A Java program can read a binary file to get numeric data, manipulate the data arithmetically, and write the data to a binary file without any intermediate conversions.

slide8

FileOperations

There are three basic operations that you will need to perform when working with disk files:

•Open the file for input or output.

•Process the file, by reading from or writing to the file.

•Close the file.

files and streams
Files and Streams
  • Java views each file as a sequential stream of bytes
  • Operating system provides mechanism to determine end of file
    • End-of-file marker
    • Count of total bytes in file
    • Java program processing a stream of bytes receives an indication from the operating system when program reaches end of stream

Fig. 14.2 | Java’s view of a file of n bytes.

files and streams1
Files and Streams
  • File streams
    • Byte-based streams – stores data in binary format
      • Binary files – created from byte-based streams, read by a program that converts data to human-readable format. 5 is (101)
    • Character-based streams – stores data as a sequence of characters
      • Text files – created from character-based streams, can be read by text editors. 5 is (00000000 00110101) – unicode representation
  • Java opens file by creating an object and associating a stream with it
class file
Class File
  • Class File useful for retrieving information about files and directories from disk
  • Objects of class File do not open files or provide any file-processing capabilities
creating file objects
Creating File Objects
  • Class File provides four constructors:
    • Takes String specifying name and path (location of file on disk)
    • Takes two Strings, first specifying path and second specifying name of file
    • Takes File object specifying path and String specifying name of file
    • Takes URI object specifying name and location of file
  • Different kinds of paths
    • Absolute path – contains all directories, starting with the root directory, that lead to a specific file or directory
    • Relative path – normally starts from the directory in which the application began executing
error prevention tip

Use File method isFile to determine whether a File object represents a file (not a directory) before attempting to open the file.

Error-Prevention Tip
demonstrating class file
Demonstrating Class File
  • Common File methods
    • exists – return true if file exists where it is specified
    • isFile – returns true if File is a file, not a directory
    • isDirectory – returns true if File is a directory
    • getPath – return file path as a string
    • list – retrieve contents of a directory
  • Separator character – used to separate directories and files in a path
    • Windows uses \
    • UNIX uses /
    • Java process both characters, File.pathSeparator can be used to obtain the local computer’s proper separator character
outline

Create new File object; user specifies file name and path

Returns true if file or directory specified exists

Retrieve name of file or directory

Retrieve path entered as a string

Returns true if name is a file, not a directory

Returns true if name is a directory, not a file

Returns true if path was an absolute path

Retrieve time file or directory was last modified (system-dependent value)

Retrieve length of file in bytes

Retrieve parent directory (path where File object’s file or directory can be found)

Retrieve absolute path of file or directory

Outline

FileDemonstration

.java

(1 of 2)

outline1

Returns true if File is a directory, not a file

Retrieve and display contents of directory

Outline

FileDemonstration

.java

(2 of 2)

outline2
Outline

FileDemonstration

Test.java

(1 of 3)

outline3
Outline

FileDemonstration

Test.java

(2 of 3)

outline4
Outline

FileDemonstration

Test.java

(3 of 3)

common programming error

Using \ as a directory separator rather than \\ in a string literal is a logic error. A single \ indicates that the \ followed by the next character represents an escape sequence. Use \\ to insert a \ in a string literal.

Common Programming Error
slide23

Low-Level File I/O•

  • To read data from or write data to a file, we must create one of the Java stream objects and attach it to the file.
  • A stream is a sequence of data items (sequence of characters or bytes) used for program input or output. Java provides many different input and output stream classes in the java.io API.
  • A file stream is an object that enables the flow of data between a program and some I/O device or file
slide24

Low-Level File I/O

–Java has two types of streams: an input stream and an output stream.

–If the data flows into a program, then the stream is called an input stream

–If the data flows out of a program, then the stream is called an output stream

opening a file
Opening a File
  • A file stream provides a connection between your program and the outside world. Opening a file makes the connection between a logical program object and a physical file via the file stream.

FileOutputStream data

Logical File Object

Physical Disk File

FileInputStream data

slide26

Streams for Low-Level File I/OBinary File Stream Classes

(Byte I/O)

  • FileInputStreamTo open a binary input stream and connect it to a physical disk file:
  • Constructor takes a String or File object.
  • Method to read: int read() OR void read(byte[])
  • FileOutputStreamTo open a binary output stream and connect it to a physical disk file:
  • Constructor takes a String or File object.
  • Method to write: void write( int ) OR void write( byte[] )
  • BOTH CLASSES READ/WRITE ONE BYTE AT A TIME
slide27

Streams for Low-Level File I/OBinary File Stream Classes

(Byte I/O)

DataInputStreamTo read binary data from a stream

DataOutputStreamTo write binary data to a stream

slide28

A File Has Two Names

•Every input file and every output file used by a program has two names:

1.The real file name used by the operating system

2.The name of the stream that is connected to the file

•The actual file name is used to connect to the stream

•The stream name serves as a temporary name for the file, and is the name that is primarily used within the program

slide29

Opening a File

A file stream provides a connection between your program and the outside world. Opening a file makes the connection between a logical program object and a physical file via the file stream.

slide30

Opening a Binary File for Output

Using the FileOutputStream class, create a file stream and connect it to a physical disk file to open the file. We can output only a sequence of bytes.

slide31

Opening a Binary File for Output

Import java.io.*;

public class TestFileOuputStream{

public static void main (String [] args) throws IOException{

//set up file and stream

File F = new File("sample1.data");

File OutputStream OutF = new FileOutputStream(F );

//data to save

byte[] A = {10, 20, 30, 40,50, 60, 70, 80};

//write the whole byte array at once to the stream

OutF.write(A );

//output done, so close the stream

OutF.close();}}

opening a binary file for input
Opening a Binary File for Input

Using the FileInputStream class, create a file stream and connect it to a physical disk file to open the file.

slide33

Opening a Binary File for Input

Import java.io.*;

public class TestFileInputStream{

public static void main (String [] args) throws IOException {

//set up file and stream

File G = new File("sample1.data");

FileInputStream InG = new FileInputStream(G);

/ /set up an array to read data in

Int fileSize= (int) G.length();

byte[] B = newbyte[fileSize];

//read data in and display them

InG.read(B);

for(int i = 0; i < fileSize; i++) {

System.out.println(B[i]);

}

//input done, so close the stream

InG.close() ; } }

slide34

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class CopyBytes {

public static void main(String[] args) throws IOException {

FileInputStream in = null;

FileOutputStream out = null;

try {

in = new FileInputStream("xanadu.txt");

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

int c;

while ((c = in.read()) != -1) {

out.write(c);

}

} finally {

if (in != null) {

in.close();

}

if (out != null) {

out.close();

}

}

}

}

streams for high level file i o
Streams for High-Level File I/O
  • •FileOutputStream and DataOutputStream are used to output primitive data values
  • •FileInputStream and DataInputStream are used to input primitive data values
  • •To read the data back correctly, we must know the order of the data stored and their data types
setting up dataoutputstream a standard sequence to set up a dataoutputstreamobject
Setting up DataOutputStreamA standard sequence to set up a DataOutputStreamobject:
  • Create a File object
  • Create a FileOutputStream object wrapped around the File object
  • Create a DataOutputStream object wrapped around the FileOutputStream object.
  • DataOutputSStream out = new DataOutputStream( new FileOutputStream( new File(“sample.dat”)));
slide38

Import java.io.*;

public class TestDataOutputStream{

public static void main (String[] args) throws IOException {

//set up file and stream

File F = newFile("sample3.data");

FileOutputStreamOutF= newFileOutputStream(F );

DataOutputStreamDF = newDataOutputStream(OutF);

//write values of primitive data types to the stream DF.

DF.writeByte(12);

DF.writeInt(1234);

DF.writeLong(9876543);

DF.writeFloat(1234F);

DF.writeDouble(1234.4565345);

DF.writeChar('A');

DF.writeBoolean(false);

//output done, so close the stream

DF.close(); } }

setting up datainputstream a standard sequence to set up a datainputstreamobject
Setting up DataInputStreamA standard sequence to set up a DataInputStreamobject:
  • Create a File object
  • Create a FileInputStream object wrapped around the File object
  • Create a DataInputStream object wrapped around the FileInputStream object.
  • DataInputStream in = new DataInputStream( new FileInputStream( new File(“sample.dat”)));
slide40

Import java.io.*;

public class TestDataInputStream {

public static void main (String[] args) throws IOException{

//set up in DataStream

File G = new File("sample3.data");

FileInputStream InF = new FileInputStream(G );

DataInputStream DF = new DataInputStream(InF);

//read values back from the stream and display them

System.out.println(DF.readByte());

System.out.println(DF.readInt());

System.out.println(DF.readLong());

System.out.println(DF.readFloat());

System.out.println(DF.readDouble());

System.out.println(DF.readChar());

System.out.println(DF.readBoolean());

//input done, so close the stream

DF.close(); } }

slide41

/*output after reading file sample3.dtat“

12

1234

9876543

1234.0

1234.4565345

A

true

************************

reading data back in right order
Reading Data Back in Right Order

The order of write and read operations must match in order to read the stored primitive data back correctly

text file input and output
Text file Input and Output
  • Instead of storing primitive data values as binary data in a file, we can convert and store them as a string data.

This allows us to view the file content using any text editor

  • To output data as a string to file, we use a FileWriter object.
  • To input data from a textfile, we use FileReader and BufferedReader classes

From Java 5.0 (SDK 1.5), we can also use the Scanner class for inputting text files

text file input and output1
Text file Input and Output

The following classes will be covered for textfile I/O:

  • FileReader
  • FileWriter
  • Scanner
  • Formatter
text file stream classes
Text File Stream Classes
  • FileReader - To open a character input stream and connect it to a physical disk file
    • Constructor param : File object OR String
    • Method to read : int read()
  • FileWriter - To open a character output stream and connect it to a physical disk file
    • Constructor param : String
    • Method to write: void write( int)
text file stream classes1
Text File Stream Classes

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException; 

public class CopyCharacters {

public static void main(String[] args) throws IOException {

FileReader inputStream = null;

FileWriter outputStream = null; 

try { inputStream = new FileReader("xanadu.txt");

outputStream = new FileWriter("characteroutput.txt"); 

int c;

while ((c = inputStream.read()) != -1) {

outputStream.write(c); } }

finally { if (inputStream != null) { inputStream.close(); }

if (outputStream != null) { outputStream.close(); } } }}

character streams that use byte streams
Character Streams that Use Byte Streams

Character streams are often "wrappers" for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.

text file stream classes2
Text File Stream Classes
  • Scanner – to read text files, the constructor expects a file object.
  • Formatter – to write text files, the constructor expects a String object.
text file stream classes3
Java imposes no structure on a file, records do not exist as part of the Java language

Programmer must structure files

Formatter class can be used to open a text file for writing

Pass name of file to constructor

If file does not exist, will be created

If file already exists, contents are truncated (discarded)

Use method format to write formatted text to file

Use method close to close the Formatter object (if method not called, OS normally closes file when program exits)

Text File Stream Classes
slide50
Possible exceptions

SecurityException – occurs when opening file using Formatter object, if user does not have permission to write data to file

FileNotFoundException – occurs when opening file using Formatter object, if file cannot be found and new file cannot be created

NoSuchElementException – occurs when invalid input is read in by a Scanner object

FormatterClosedException – occurs when an attempt is made to write to a file using an already closed Formatter object

sample textfile ouput with formatter
Sample Textfile Ouput with Formatter

import java.util.*;

import java.io.*;

class TestFormatter{

public static void main (String[] args) throws IOException{

Scanner input = new Scanner(System.in);

Formatter output = new Formatter("sample3.data“);

int i = input.nextInt(); long l = input.nextLong(); float f = input.nextFloat();

double d = input.nextDouble(); char c = input.next().charAt(0);

output.format( "%d %d %.2f %10.2f %c\n”, i, l, f, d, c);

output.close(); } }

sample textfile input with scanner
Sample Textfile Input with Scanner

import java.util.*;

import java.io.*;

class TestScanner{

public static void main (String[] args) throws IOException{

//open the Scanner

try{

Scanner input = new Scanner(new File("sample3.data"));}

catch (FileNotFoundException e) {

System.out.println(“Error opening file”);

System. Exit(1); }

int i = input.nextInt(); long l = input.nextLong(); float f = input.nextFloat();

double d = input.nextDouble(); char c = input.next().charAt(0);

System.out.printf("%d %d %.2f %10.2f %c\n”, i, l, f, d, c);

input.close(); } }

slide53

import java.io.*;

  • import java.util.Scanner; 
  • public class ScanXan {
  • public static void main(String[] args) throws IOException {
  • Scanner s = null;
  • try {
  • s = new Scanner(new File ("xanadu.txt")));
  • while (s.hasNext()) {
  • System.out.println(s.next()); } }
  • finally { if (s != null) { s.close(); } }
  • } }
object serialization
Object Serialization
  • With text files, data type information lost
  • Object serialization – mechanism to read or write an entire object from a file
  • Serialized object – object represented as sequence of bytes, includes object’s data and type information about object
  • Deserialization – recreate object in memory from data in file
  • Serialization and deserialization performed with classes ObjectInputStream and ObjectOutputStream, methods readObject and writeObject
creating a sequential access file using object serialization
Creating a Sequential-Access File Using Object Serialization:
  • Serializable interface – programmers must declare a class to implement the Serializable interface, or objects of that class cannot be written to a file
  • To open a file for writing objects, create a FileOutputStream wrapped by an ObjectOutputStream
common programming error1
Common Programming Error
  • It is a logic error to open an existing file for output when, in fact, the user wishes to preserve the file.
reading and deserializing data from a sequential access file
Reading and Deserializing Data from a Sequential-Access File
  • To open a file for reading objects, create a FileInputStream wrapped by an ObjectInputStream
    • ObjectInputStream method readObject reads in object, which is then downcast to proper type
      • EOFException occurs if attempt made to read past end of file
      • ClassNotFoundException occurs if the class for the object being read cannot be located
    • ObjectInputStream method close closes both objects
saving objects
Saving Objects
  • To save objects to a file, we first create an ObjectOutputStream object. Method to write object: void writeObject(Object)
  • import java.io.*;
  • class Test{
  • Public static void main(String[] args) throws IOException {
  • File out = new File(“ obj.dat”);
  • FileOutputStream fos = new ObjectOutputStream (out);
  • ObjectOutputStream oos = new ObjectOutputStream (fos);
  • Person p;
  • String s1, s2
  • for (int j = 0; j<10; j++) {

s1 = input.next(); s2 = input.next();

p = new Person ( s1 , s2 );

oos.writeObject(p); }

oos.close();

CLASS PERSON MUST IMPLEMENT SERIALIZABLE INTERFACE

Public class Person implements Serializable { …. }

reading objects
Reading Objects

To read objects from a file, we use FileInputStream and ObjectInputStream. Method to read object: Object readObject()

import java.io.*;

class Test{

Public static void main(String[] args) throws Exception{

ObjectInputStream in= new ObjectInputStream( new FileInptStream( new File(“obj.dat”) ))

Person p;

for (int j=0 ; j<10; j++) {

p = (Person) in.readObject();

System.out.println(p); }

In.close(); }}

example if number of records in file are not known
Example: (if number of records in file are not known)

import java.io.*;

class Test{

Public static void main(String[] args) throws Exception{

ObjectInputStream in= new ObjectInputStream( new FileInptStream( new File(“obj.dat”) ))

Person p;

Try

{

while (true) {

p = (Person) in.readObject();

System.out.println(p);

} // end while

} // end try

catch ( EOFException endOfFileException )

{

System.out.println(); // end of file was reached

} // end catch

in.close(); }}

saving and loading arrays
Saving and Loading Arrays

Arrays can be processed as a whole:

Person[] p = new Person[5] ;

….

out.writeObject(p);

Person[] p = (Person[]) in.readObject();

interfaces and classes for byte based input and output
Interfaces and Classes for Byte-Based Input and Output
  • Buffering is an I/O-performance-enhancement technique
    • Greatly increases efficiency of an application
    • Output (uses BufferedOutputStream class)
      • Each output statement does not necessarily result in an actual physical transfer of data to the output device – data is directed to a region of memory called a buffer (faster than writing to file)
      • When buffer is full, actual transfer to output device is performed in one large physical output operation (also called logical output operations)
      • Partially filled buffer can be forced out with method flush
    • Input (uses BufferedInputStream class)
      • Many logical chunks of data from a file are read as one physical input operation (also called logical input operation)
      • When buffer is empty, next physical input operation is performed
interfaces and classes for character based input and output
Interfaces and Classes for Character-Based Input and Output
  • Reader and Writer abstract classes
    • Unicode two-byte, character-based streams
  • BufferedReader and BufferedWriter classes
    • Enable buffering for character-based streams
  • CharArrayReader and CharArrayWriter classes
    • Read and write streams of characters to character arrays
  • LineNumberReader class
    • Buffered character stream that keeps track of number of lines read
  • PipedReader and PipedWriter classes
    • Implement piped-character streams that can be used to transfer information between threads
  • StringReader and StringWriter classes
    • Read characters from and write characters to Strings