Chapter 10: I/O Streams Input Streams Output Streams

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

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.
Jan Java I/O Yangjun Chen Dept. Business Computing University of Winnipeg.
Introduction to Java 2 Programming Lecture 7 IO, Files, and URLs.
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.
Simple Java I/O Part I General Principles. 2 Streams All modern I/O is stream-based A stream is a connection to a source of data or to a destination for.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L07 (Chapter 18) Binary I/O.
Algorithm Programming I/O via Java Streams Bar-Ilan University תשס"ח by Moshe Fresko.
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.
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.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
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
Program data (instance variables, local variables, and parameters) is transient, because its lifetime ends with the program...if not, before. Sometimes.
Copyright © Curt Hill Java I/O Flexibility and Layering.
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.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Input/output Input in java is stream based.A stream represents sequence of bytes or characters. Stream provides an abstract view of I/O. Stream can be.
L5: Input & Output COMP206, Geoff Holmes and Bernhard Pfahringer.
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.
A stream is a sequence of data. A stream is a flowing sequence of characters.
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.
Java IO. Why IO ? Without I/O, your program is a closed box. Without I/O, your program is a closed box. I/O gives your Java program access to your hard.
Copyright(c) Systems and Computer Engineering, Carleton Univeristy, * Object-Oriented Software Development Unit 13 I/O Stream Hierarchy Case.
1 Streams Chapter Nineteen. 2 What are streams? l Input and Output for example from the keyboard (a standard input device) or the CRT (a standard output.
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
Company Input/Output Stream –. Input/Output Stream Data Program Input Stream Output Stream.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
1 Putting Streams to use. 2 Stream Zoo C++ gives you istream, ostream, iostream, ifstream, ofstream, fstream, wistream, wifstream, istrsteam… (18) Java.
File Input & Output1 Streams & File I/O. Introduction (1) The Java platform includes a number of packages that are concerned with the movement of data.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
Java Programming Language (3) - Input/Output Stream –
CS202 Java Object Oriented Programming Input and Output Chengyu Sun California State University, Los Angeles.
Generics and file handling Presented by: Abha Kumari Neha Pradip Vhanmane Raj Visa Rashmi Kewlani Suvrat Dixit.
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.
Sequential files creation & writing
IO in java.
Chapter 17 Input and Output
Exception Handling, Reading and Writing in Files, Serialization,
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.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Programming in Java Files and I/O Streams
CS 116 Object Oriented Programming II
Објектно орјентисано програмирање
Chapter 17 Binary I/O Dr. Clincy - Lecture.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
OBJECT ORIENTED PROGRAMMING II LECTURE 11_1 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
CS 240 – Advanced Programming Concepts
David Davenport Spring 2005
Presentation transcript:

Chapter 10: I/O Streams Input Streams Output Streams File streams (File input and File) Filters (Data input and output) File class FileDialog class

Input/Output Cannot expect user to enter all information when starting program (airline program -- enter all flight info??) Stream - a sequence of characters (either as input or output that we can perform operations to) write a char read a char read a sequence of chars

Streams generally connected to files (using FileInputStream or FileOutputStream) Can also be connected to other objects (Strings, other streams, etc.) DataInputStream and DataOutputStream are streams that allow more complex manipulations Include java.io.*;

InputStream Abstract class Methods: int available() throws IOException - returns 0, can be overridden, indicates # available chars void close() throws IOException - close stream long skip(long n) throws IOException - skip the next n characters

InputStream methods: int read() throws IOException - gets the next available char from the stream, -1 if none int read(byte[] bArray) throws IOException, NullPointerException - trys to fill array, returns the number of characters read int read(byte[] bArray, int offset, int length) throws IOException, NullPointerException, IndexOutOfBoundsException - trys to fill array starting at position offset with up to length chars, returns the number read

OutputStream Abstract class Methods: void close() throws IOException - close stream long flush() throws IOException - flush buffer void write(int c) throws IOException - write char c to stream void write(byte[] bArray) throws IOException, NullPointerException - writes the array of chars void write(byte[] bArray, int offset, int length) throws IOException, NullPointerException, IndexOutOfBoundsException - writes length chars starting at offset to stream

FileInputStream InputStream connected to a file constructors: methods: FileInputStream(String fname) throws FileNotFoundException, SecurityException - opens InputStream connected to fname FileInputStream(File f) throws FileNotFoundException, SecurityException - same as above using File class (more later) methods: implements methods of InputStream: available, close, skip, 3 reads

FileOutputStream OutputStream connected to a file constructors: FileOutputStream(String fname) throws FileNotFoundException, SecurityException - opens OutputStream connected to fname FileOutputStream(File f) throws FileNotFoundException, SecurityException - same as above using File class (more later) methods: implements methods of OutputStream: close, flush, 3 writes

void copyFile(String srcF, String dstF) { try { FileInputStream inf = new FileInputStream(srcF); FileOutputStream outf = newFileOutputStream(dsfF); int ch; while ((ch = inf.read()) != -1) outf.write(ch); inf.close(); outf.close(); } catch (Exception e) { // Announce unable to open files

Other InputStream Classes ByteArrayInputStream - connected to an array of bytes StringBufferInputStream - connected to a string of characters PipedInputStream - connected to a pipe command

Other Output Stream Classes ByteArrayOutputStream - connected to an array of bytes PipedOutputStream - feeding chars to a pipe command

Filter Classes Java also provides filter classes These classes are connected to an input or output stream and allow interpretation of the input/output Most prevalent are DataInputStream and DataOutputStream

DataInputStream Connected to an InputStream (often file) Constructor: DataInputStream(InputStream in) Methods: boolean readBoolean() throws IOException - reads info corresponding to a boolean (1 byte) similar routines for Byte, Char, Double, Float, Int, Long, Short

DataInputStream (cont) More methods: int readFully(byte[] bArray) throws IOException, NullPointerException - read in array of chars stopping when full or at EOF String readLine() throws IOException - read as a string the next sequence of chars until a newline encountered void skipBytes(int n) throws IOException - skip the next n bytes

DataOutputStream Connected to an OutputStream (often file) Constructor: DataOutputStream(OutputStream in) Methods: void writeBoolean(boolean b) throws IOException - writes b to file similar routines for Byte, Char, Double, Float, Int, Long, Short

DataOutputStream (cont) More methods: void writeBytes(byte[] barray) throws IOException - write array of bytes void writeBytes(String s) throws IOException - write string as array of bytes void writeChars(String s) throws IOException - similar to writeBytes for string arg

class Employee { private int idnum; private float salary; private String name; void writeToFile(DataOutputStream s) throws IOException { s.writeInt(idnum); s.writeFloat(salary); s.writeString(name + “\n”); } void readFromFile(DataInputStream s) throws IOException idnum = s.readInt(); salary = s.readFloat(); name = s.readLine();

void writeEmployeeFile(String fname, Employee[] bees, int numEmployees) { try { FileOutputStream fos = new FileOutputStream(fname); DataOutputStream fstream = new DataOutputStream(fos); int e; fstream.writeInt(numEmployees); for (e = 0; e < numEmployees; e++) bees[e].writeToFile(fstream); fstream.close(); } catch IOException { // report that something went wrong

int readEmployeeFile(String fname, Employee[] bees) { try { FileInputStream fis = new FileInputStream(fname); DataInputStream fstream = new DataInputStream(fis); int e; int numEmployees; numEmployees = fstream.readInt(); for (e = 0; e < numEmployees; e++) bees[e].readFromFile(fstream); fstream.close(); return numEmployees; } catch IOException { // report that something went wrong

Other Useful Filters BufferedInputStream, BufferedOutputStream - reduces I/O with buffering LineNumberInputStream - adds the feature of knowing the line number as lines read PushbackInputStream - implements a one char “push back” buffer - good for parsing

File Class Mechanism for exploring files (often used to avoid having exceptions thrown when files not found) Constructor: File(String name) - produces a File instance even if the name is not a legal file name

Methods: boolean exists() - true if file already exists boolean isDirectory() - true if directory file boolean isFile() - true if data file boolean canRead() - true if file can be read boolean canWrite() - true if file can be written long lastModified() - returns a number indicating last modification time (no given structure)

Methods: long length() - number of bytes in file boolean equals(Object obj) - true if arg is file with same name String[] list() - returns list of files in directory String[] list(FileNameFilter f) - returns list of acceptable files from directory boolean delete() - attempts to delete, true if success

FileNameFilter Interface Restrict files in File, FileDialog classes Implements one method: boolean accept(File directory, String name) - true if this directory, name acceptable Example class JavaSrcFilter implements FileNameFilter { boolean accept(File d, String s) { if (s.endswith(“.java”)) return true; else return false; }

FileDialog Produces a Dialog box that can be used to select files (look depends on system) In java.awt.FileDialog constants: LOAD, SAVE (modes) constructors: FileDialog(Frame Parent, String mssg) - mssg used to prompt, must have parent frame FileDialog(Frame Parent, String mssg, int mode) - mode is one of FileDialog.LOAD or SAVE, indicates expected use of file

Methods: String getDirectory() - string corresponding to directory selected File getFile() - File object corresponding to file selected void setFileNameFilter(FileNameFilter f) - set filter used to select files void setDirectory(String s) - set initial directory void setFile(String s) - set initial file void getFileNameFilter() - get current filter (null if none)