1 Streams and Input/Output Files Part 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

I/O Basics 12 January 2014Smitha N. Pai, CSE Dept.1.
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
1 Streams and Input/Output Files Part I. 2 Introduction So far we have used variables and arrays for storing data inside the programs. This approach poses.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 12 File Input and Output Animated Version.
Chapter 19 Binary I/O.
Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Lecture 15: I/O and Parsing
Exceptions. Definition Exception: something unexpected that can occur in the execution of a program e.g., divide by zero or attempt to open a file that.
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Chapter 10 Ch 1 – Introduction to Computers and Java Streams and File IO 1.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
Files Files are used to store long term data. –Typically referred to as persistent data. –A file is a group of related records. –A list of friends addresses.
 We can use a combination of the File and FileOutputStream to write a series of bytes to a file.
Using Processing Stream. Predefined Streams System.in InputStream used to read bytes from the keyboard System.out PrintStream used to write bytes to the.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
File I/O in Java CS 311, Winter File Basics Recall that a file is block structured. What does this mean? What happens when an application opens.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 18 Binary I/O.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Java I/O Input: information brought to program from an external source
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Use JFileChooser F Text Input.
Streams and Files CMPS Overview Stream classes File objects File operations with streams Examples in C++ and Java 2.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Input / Output Chapter 13.  We use files all the time  Programs are files  Documents are files  We want them to be “permanent”  To last beyond execution.
Chapter 17 Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams  Use JFileChooser F Text Input.
Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Text Input and Output on the Console.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Chapter 15 – Files I/O basics File I/O Classes File I/O Basic Operations Text File Output PrintWriter import Statement with a * Text File Input Scanner,
Files and Streams. Midterm exam Time: Wednesday, October 31, 2007 Format: Multiple choices (about 15 to 20 questions) Determine the results of the code.
JAVA I/O © EnhanceEdu, IIIT Hyderabad. Contents 3/29/2010EnhanceEdu, IIIT - H 2  Command Line I/O  File Class  Streams  Byte Streams [Low level and.
L5: Input & Output COMP206, Geoff Holmes and Bernhard Pfahringer.
Two Ways to Store Data in a File  Text format  Binary format.
Java Input/Output. Reading standard input Surprisingly complicated (GUI focus) Old-fashioned way: BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.
Streams and File I/O Chapter 9. Outline Overview of Streams and File I/O Text-File I/O Using the File Class Basic Binary-File I/O Object I/O with Object.
Lecture 5 I/O and Parsing
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
1 Chapter 19 Binary I/O. 2 Motivations F Data stored in a text file – is represented in human-readable form –Text file –Readable –Java source programs.
Chapter 15: Input and Output F Stream Classes F Processing External Files F Data Streams F Print Streams F Buffered Streams F Parsing Text Files F Random.
Chapter 15: Input and Output
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Java Input/Output. Java Input/output Input is any information that is needed by your program to complete its execution. Output is any information that.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
Java Input / Output l a modular approach to input/output: - different stream objects are connected/wrapped to handle I/O l a data stream object: a flow.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Java I/O 1. Java I/O (Input and Output) is used to process the input and produce the output based on the input. The java.io package contains all the classes.
Java Programming, Second Edition Chapter Sixteen File Input and Output.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Java IO Exploring the java.io package and living to talk about it.
The Java IO System Different kinds of IO Different kinds of operations
Fundamental of Java Programming
IO in java.
IO in java.
Chapter 17 Input and Output
OO Design and Programming II I/O: Reading and Writing
Chapter 17 Binary I/O.
Object Writing in files
OBJECT ORIENTED PROGRAMMING II LECTURE 21_1 GEORGE KOUTSOGIANNAKIS
I/O Basics.
Chapter 17 Binary I/O 1.
File.
JAVA IO.
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
The Package Statement Group related interfaces and classes together
David Davenport Spring 2005
Presentation transcript:

1 Streams and Input/Output Files Part 3

2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used for reading/writing bytes or characters. To read/write the primitive data types such as integers and doubles, we can use filter classes as wrappers on the existing I/O streams to filter data to the original stream. The two filter classes supported for creating data streams for primitive data types are: DataInputStream DataOutputStream

3 Hierarchy of Data Stream Classes FilterInputStreamDataInput DataInputStream ClassInterface FilterOutputStreamDataOutput DataOutputtStream ClassInterface

4 Data Input Stream Creation Create Input File Stream: FileInputStream fis = new FileInputStream(InFile); Create Input Data Stream: DataInputStream dis = new DataInputStream( fis ); The above statements wrap data input stream (dis) on file input stream (fis) and use it as a filter. Methods Supported: readBoolean(), readByte(), readChar(), readShort(), readInt(), readLong(), readFloat(), readDouble() They read data stored in file in binary format.

5 Data Output Stream Creation Create Output File Stream: FileOutputStream fos = new FileOutputStream(OutFile); Create Output Data Stream: DataOutputStream dos = new DataOutputStream( fos ); The above statements wrap data output stream (dos) on file output stream (fos) and use it as a filter. Methods Supported: writeBoolean(), writeByte(), writeChar(), writeShort(), writeInt(), writeLong(), writeFloat(), writeDouble() They write data to file in binary format. How many bytes are written to file when for statements: writeInt(120), writeInt(10120)

6 Data Streams Flow via Filter Write primitive data to the file using a filter. Read primitive data from the file using a filter. Program dosfos mydata filter binary stream Program fisdis mydata binary stream filter Screen

7 Writing and Reading Primitive Data import java.io.*; public class ReadWriteFilter { public static void main(String args[]) throws IOException { // write primitive data in binary format to the "mydata" file FileOutputStream fos = new FileOutputStream("mydata"); DataOutputStream dos = new DataOutputStream(fos); dos.writeInt(120); dos.writeDouble(375.50); dos.writeInt('A'+1); dos.writeBoolean(true); dos.writeChar('X'); dos.close(); fos.close(); // read primitive data in binary format from the "mydata" file FileInputStream fis = new FileInputStream("mydata"); DataInputStream dis = new DataInputStream(fis); System.out.println(dis.readInt()); System.out.println(dis.readDouble()); System.out.println(dis.readInt()); System.out.println(dis.readBoolean()); System.out.println(dis.readChar()); dis.close(); fis.close(); }

8 Program Run and Output C:\254\examples>java ReadWriteFilter true X Display content of mydata file (in binary format): C:\254\examples>type mydata B X What is the size of mydata file (in bytes) ? Size of int+double+int+boolean+char

9 Concatenating and Buffering Streams Two or more input streams can be combined into a single input stream. This process is known as logical concatenation of streams and is achieved using the SequenceInputStream class. A SequenceInputStream starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file is reached on the last of the contained input streams.

10 Sequencing and Buffering of Streams Buffered streams sit between the program and data source/destination and functions like a filter or support efficient I/O. Buffered can be created using BufferedInputStream and BufferedOutputStream classes. Program file1+file2 Buffer file1.dat Streams Sequencer Screen file2.dat read() Buffer write() inBuffer outputBuffer

11 Example Program import java.io.*; public class CombineStreams { public static void main(String args[]) throws IOException { // declare file streams FileInputStream file1 = new FileInputStream("file1.dat"); FileInputStream file2 = new FileInputStream("file2.dat"); // declare file3 to store combined streams SequenceInputStream file3 = null; // concatenate file1 and file2 streams into file3 file3 = new SequenceInputStream(file1, file2); BufferedInputStream inBuffer = new BufferedInputStream(file3); BufferedOutputStream outBuffer = new BufferedOutputStream(System.out); // read and write combined streams until the end of buffers int ch; while((ch = inBuffer.read()) != -1 ) outBuffer.write(ch); outBuffer.flush(); // check out the output by removing this line System.out.println("\nHello, This output is generated by CombineFiles.java program"); inBuffer.close(); outBuffer.close(); file1.close(); file2.close(); file3.close(); }

12 Contents of Input Files The file1.dat contains: Hello, I am C++, born in AT&T. The file2.dat contains: Hello, I am Java, born in Sun Microsystems!

13 Output C:\254\examples>java CombineStreams Hello, I am C++, born in AT&T. Hello, I am Java, born in Sun Microsystems! Hello, This output is generated by CombineFiles.java program If the statement outBuffer.flush() is removed, the output will be: Hello, This output is generated by CombineFiles.java program Hello, I am C++, born in AT&T. Hello, I am Java, born in Sun Microsystems!

14 Random Access Files So for we have discussed sequential files that are either used for storing data and accessed (read/write) them in sequence. In most real world applications, it is necessary to access data in non-sequential order (e.g, banking system) and append new data or update existing data. Java IO package supports RandomAccessFile class that allow us to create files that can be used for reading and/or writing with random access. The file can be open either in read mode (r) or read- write mode (rw) as follows: myFileHandleName = new RandomAccessFile (filename, mode); The file pointer can be set to any to any location (measured in bytes) using seek() method prior to reading or writing.

15 Random Access Example import java.io.*; public class RandomAccess { public static void main(String args[]) throws IOException { // write primitive data in binary format to the "mydata" file RandomAccessFile myfile = new RandomAccessFile("rand.dat", "rw"); myfile.writeInt(120); myfile.writeDouble(375.50); myfile.writeInt('A'+1); myfile.writeBoolean(true); myfile.writeChar('X'); // set pointer to the beginning of file and read next two items myfile.seek(0); System.out.println(myfile.readInt()); System.out.println(myfile.readDouble()); //set pointer to the 4th item and read it myfile.seek(16); System.out.println(myfile.readBoolean()); // Go to the end and append an integer 2003 myfile.seek(myfile.length()); myfile.writeInt(2003); // read 5th and 6th items myfile.seek(17); System.out.println(myfile.readChar()); System.out.println(myfile.readInt()); System.out.println("File length: "+myfile.length()); myfile.close(); } Int Double Int boolean Char Int

16 Execution and Output C:\254\examples>java RandomAccess true X 2003 File length: 23

17 Streams and Interactive I/O Real world applications are designed to support interactive and/or batch I/O operations. Interactive programs allow users to interact with them during their execution through I/O devices such as keyboard, mouse, display devices (text/graphical interface), media devices (microphones/speakers), etc.. Java provides rich functionality for developing interactive programs. Batch programs are those that are designed to read input data from files and produce outputs through files.

18 Standard I/O The System class contains three I/O objects (static) System.in – instance of InputStream System.out – instance of PrintStream System.err – instance of PrintStream To perform keyboard input, we need use functionalities of DataInputStream and StringTokenizer classes.

19 Reading Integer from Standard Input Create buffered reader for standard input by wrapping System.in object: BufferedReader dis = new BufferedReader(new InputStreamReader(System.in)); Read a line of text from the console String str = dis.readLine(); Create Tokenens StringTokenizer st; st = new StringTokenizer(str); Convert String Token into basic integer: int stdID = Integer.parseInt(st.nextToken());

20 Interactive IO Example import java.io.*; import java.util.*; public class StudentRecord { public static void main(String args[]) throws IOException { // Create buffered reader for standard input BufferedReader dis = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; // reading data from console System.out.print("Enter Student ID: "); st = new StringTokenizer(dis.readLine()); int stdID = Integer.parseInt(st.nextToken()); System.out.print("Enter Student Name: "); String stdName = dis.readLine(); System.out.print("Enter Student Marks: "); st = new StringTokenizer(dis.readLine()); int stdMarks = Integer.parseInt(st.nextToken()); // write to console System.out.println("Student details are:"); System.out.println("ID: "+stdID); System.out.println("Name: "+stdName); System.out.println("Marks: "+stdMarks); }

21 Run and Output C:\254\examples>java StudentRecord Enter Student ID: Enter Student Name: Mary Baker Enter Student Marks: 85 Student details are: ID: Name: Mary Baker Marks: 85

22 Summary All Java I/O classes are designed to operate with Exceptions. User Exceptions and your own handler with files to manger runtime errors. Subclasses FileReader / FileWriter support characters- based File I/O. FileInputStream and FileOutputStream classes support bytes-based File I/O. Buffered read/write operations support efficient I/O. DataInputStream and DataOutputStream classes support rich I/O functionality. RandomAccessFile supports access to any data items in files in any order.