Download presentation
Presentation is loading. Please wait.
1
Files and Streams
2
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
3
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
4
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
5
Data Hierarchy Fields – a group of characters or bytes that conveys meaning Record – a group of related fields File – a group of related records
6
Fig | Data hierarchy.
7
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.
8
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.
9
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 | Java’s view of a file of n bytes.
10
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 ( ) – unicode representation Java opens file by creating an object and associating a stream with it
11
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
12
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
13
File methods. (Part 1 of 2)
14
| File methods. (Part 2 of 2)
15
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.
16
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
17
Outline Create new File object; user specifies file name and path
FileDemonstration .java (1 of 2) Create new File object; user specifies file name and path Returns true if file or directory specified exists Retrieve name of file or directory 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 path entered as a string Retrieve absolute path of file or directory Retrieve parent directory (path where File object’s file or directory can be found)
18
Outline Returns true if File is a directory, not a file
Retrieve and display contents of directory FileDemonstration .java (2 of 2)
19
Outline FileDemonstration Test.java (1 of 3)
20
Outline FileDemonstration Test.java (2 of 3)
21
Outline FileDemonstration Test.java (3 of 3)
22
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.
23
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
24
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
25
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
26
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: Method to write: void write( int ) OR void write( byte[] ) BOTH CLASSES READ/WRITE ONE BYTE AT A TIME
27
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
28
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
29
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.
30
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.
31
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();}}
32
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.
33
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() ; } }
34
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();
36
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
37
Setting up DataOutputStream A 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”)));
38
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( ); DF.writeFloat(1234F); DF.writeDouble( ); DF.writeChar('A'); DF.writeBoolean(false); //output done, so close the stream DF.close(); } }
39
Setting up DataInputStream A 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”)));
40
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(); } }
41
/. output after reading file sample3. dtat“ 12 1234 9876543 1234
/*output after reading file sample3.dtat“ A true ************************
42
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
43
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
44
Text file Input and Output
The following classes will be covered for textfile I/O: FileReader FileWriter Scanner Formatter
45
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)
46
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(); } } }}
47
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.
48
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.
49
Text File Stream Classes
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)
50
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
51
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(); } }
52
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(); } }
53
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(); } } } }
54
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
55
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
56
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.
57
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
58
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 { …. }
59
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(); }}
60
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(); }}
61
Saving and Loading Arrays
Arrays can be processed as a whole: Person[] p = new Person[5] ; …. out.writeObject(p); … Person[] p = (Person[]) in.readObject();
62
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
63
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.