1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
Lecture 15: I/O and Parsing
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.
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.
File Handling and Serialization CSIS 3701: Advanced Object Oriented Programming.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
Java I/O – what does it include? Command line user interface –Initial arguments to main program –System.in and System.out GUI Hardware –Disk drives ->
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Java I/O Input: information brought to program from an external source
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
Two Ways to Store Data in a File Text format Binary format.
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) –it acts as.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Working with files By the end of this lecture you should be able to: explain the principles of input and output and identify a number of different input.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
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.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
OOP with Java, David J. Barnes Input-Output1 A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated.
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.
MIT AITI 2003 Lecture 15 Streams Input and Output data from/to other sources.
I/O in Java Dennis Burford
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Chapter 9-Text File I/O. Overview n Text File I/O and Streams n Writing to a file. n Reading from a file. n Parsing and tokenizing. n Random Access n.
The Java I/O Classes and Interfaces cont’d
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
Two Ways to Store Data in a File  Text format  Binary format.
© Amir Kirsh Files and Streams in Java Written by Amir Kirsh.
A stream is a sequence of data. A stream is a flowing sequence of characters.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
Files and Streams CS /02/05 L7: Files Slide 2 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved.
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.
1 Software 1 Java I/O. 2 The java.io package The java.io package provides: Classes for reading input Classes for writing output Classes for manipulating.
Lecture 5 I/O and Parsing
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
Chapter 9 1 Chapter 9 – Part 2 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
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.
Simple Java I/O Part I General Principles. Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
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.
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Chapter 17 Input and Output
OO Design and Programming II I/O: Reading and Writing
Lesson 8: More File I/O February 5, 2008
CHAPTER 5 JAVA FILE INPUT/OUTPUT
I/O Basics.
Streams and File I/O Chapter 9 Chapter 9.
Streams and File I/O Chapter 14.
Workshop for Programming And Systems Management Teachers
Workshop for Programming And Systems Management Teachers
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
David Davenport Spring 2005
Presentation transcript:

1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as possible. –Character sets, end-of-line, path separators, endian-issues. Readers, Writers and Streams.

2 The java.io Package Classes that provide an insulation layer. –The File class hides file system differences –Reader and Writer classes perform mapping to and from Unicode. –Stream classes deliver raw byte input. –Whole objects may be read and written easily.

3 The File Class A File object represents an abstract pathname. –Represents both files and directories (folders). –Name, parent directory, size, permissions. –Constructor takes the file’s name: File info = new File("Letter.txt"); –No exception thrown if the file does not exist.

4 Methods of the File Class File info = new File("Letter.txt"); if(info.exists()){ System.out.println("Size of "+info.getName()+ " is "+info.length()); if(info.isDirectory()){ System.out.println("The file is a directory."); } if(info.canRead()){ System.out.println("The file is readable."); } if(info.canWrite()){ System.out.println("The file is writeable."); }

5 FileReader and FileWriter The two main classes for reading and writing text files. –A file is opened when its name is passed to their constructors. –Files should be closed (via close ) when finished with. –Their read and write methods deal with char and char[].

6 Opening and Closing a File try{ // Try to open the file. FileReader inputFile = new FileReader(filename); // Process the file's contents.... // Close the file now that it is finished with. inputFile.close(); } catch(FileNotFoundException e){ System.out.println("Unable to open "+filename); } catch(IOException e){ // The file could not be read or closed. System.out.println("Unable to process "+filename); }

7 Copying a Text File void copyFile(FileReader inputFile, FileWriter outputFile) throws IOException { final int bufferSize = 1024; char[] buffer = new char[bufferSize]; // Read the first chunk of characters. int numberRead = inputFile.read(buffer); while(numberRead > 0){ // Write out what was read. outputFile.write(buffer,0,numberRead); numberRead = inputFile.read(buffer); } outputFile.flush(); }

8 Reading Single Characters void copyFile(FileReader inputFile,FileWriter outputFile){ try{ // Read the first character. int nextChar = inputFile.read(); // Have we reached the end of file? while(nextChar != -1){ outputFile.write(nextChar); // Read the next character. nextChar = inputFile.read(); } outputFile.flush(); } catch(IOException e){ System.out.println("Unable to copy a file."); }

9 Input-Output Bottlenecks Input-output is generally a slow process. –Disk and network access are often involved. A single large read/write probably takes little more time than a small read/write. Buffered classes bundle multiple read/write operations into fewer. –Read more than is required. –Delay writing until more is ready.

10 Buffered Reader and Writers try{ FileReader in = new FileReader(infile); BufferedReader reader = new BufferedReader(in); FileWriter out = new FileWriter(outfile); BufferedWriter writer = new BufferedWriter(out);... reader.close(); writer.close(); } catch(FileNotFoundException e){ System.out.println(e.getMessage()); } catch(IOException e){ System.out.println(e.getMessage()); }

11 Line-by-Line Copying BufferedReader reader = new BufferedReader(...); // Read the first line. String line = reader.readLine(); // null returned on EOF. while(line != null){ // Write the whole line. writer.write(line); // Add the newline character. writer.newLine(); // Read the next line. line = reader.readLine(); }

12 The Stream Classes Several classes that deliver input as a stream of raw bytes, or write raw bytes. –BufferedInputStream, DataInputStream, FileInputStream. –BufferedOutputStream, DataOutputStream, –FileOutputStream. Their read and write methods take byte[] rather than char[] arguments.

13 Stream Readers and Writers InputStreamReader and Output- StreamWriter bridge the divide. Different file encodings supported. Constructed from an appropriate Stream. –Read/Write operations are delegated. –Read/Write operations take char arguments. Used to wrap System.in –new InputStreamReader(System.in)

14 Reading and Writing Objects We often want objects to be persistent across program runs. –Defining storage methods on a per-class basis is inefficient and error-prone. –An agreed binary format is necessary for portability. –Version control is important. Serialization: ObjectInputStream and ObjectOutputStream.

15 The StreamTokenizer Class Constructed from a Reader, to which it delegates its input requests. Returns tokens: multi-character numbers or strings. –TT_NUMBER, TT_WORD, TT_EOF. Really designed with programming language translation in mind.

16 The StringTokenizer Class Defined in the java.util package. Splits strings into separate String tokens. –Delimiter characters are user settable (whitespace by default). –Will also return delimiters if required. Simple interface –public boolean hasMoreTokens() –public String nextToken()

17 Finding Words String line = in.readLine(); while(line != null){ StringTokenizer tokenizer = new StringTokenizer(line,",;:.\"' \t"); while(tokenizer.hasMoreTokens()){ String word = tokenizer.nextToken(); // Print the next word. System.out.println(word); } line = in.readLine(); }

18 Review Input-Output is usually difficult to perform in a platform-independent way. The java.io package provides the required independence. The File class supplies details of external files. Use Reader and Writer classes for text files.

19 Review (cont.) Use Buffered classes for input-output efficiency. Use Stream classes when access to binary data is required. Stream Reader/Writer classes form a bridge between streams and readers and writers. StringTokenizer is useful for breaking up textual input.