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.

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

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.
Lecture 15: I/O and Parsing
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.
Standard input, output and error. Lecture Under Construction.
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.
Java I/O and Java Networking (Client Side) Yoshi.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 12  File Input and Output Stream Classes Text Input and Output.
Algorithm Programming I/O via Java Streams Bar-Ilan University תשס"ח by Moshe Fresko.
Java I/O Input: information brought to program from an external source
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
CS203 Programming with Data Structures Input and Output California State University, Los Angeles.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
5-Oct-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Streams and Files Maj Joel Young.
Prepared by : A.Alzubair Hassan Kassala university Dept. Computer Science Lecture 2 I/O Streams 1.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
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.
Richiami di Java Input/Output. import java.io.*; public class Simple { public static void main(String a[]){ new Simple(); } public Simple() { byte buffer[]=new.
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.
I / O in java. java.io BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter ByteArrayInputStream ByteArrayOutputStream CharArrayReader.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture.
The Java I/O Classes and Interfaces cont’d
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.
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));
© Amir Kirsh Files and Streams in Java Written by Amir Kirsh.
1 CISC 370: I/O Streams James Atlas June 24, 2008.
1 OOP Lecture 17 I/O and Graphics Signe Ellegård Borch Carsten Schuermann IT University Copenhagen.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
Copyright(c) Systems and Computer Engineering, Carleton Univeristy, * Object-Oriented Software Development Unit 13 I/O Stream Hierarchy Case.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
תוכנה 1 תרגול מס ' 4 שימוש במחלקות קיימות : קלט / פלט (IO)
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
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.
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.
1 Input-Output A complex issue in programming language design. The interface to the outside world. –Differences must be accommodated as transparently as.
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.
java.io supports console and file I/O
The Java IO System Different kinds of IO Different kinds of operations
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Files and Streams The material in this chapter is not tested on the AP CS exams.
CSG2H3 Object Oriented Programming
Java Text I/O CS140 Dick Steflik. Reader Abstract super class for character based input Subclasses: – BufferedReader – CharArrayReader – FilterReader.
IO in java.
Exception Handling, Reading and Writing in Files, Serialization,
Ch14 Files and Streams OBJECTIVES
12: The Java I/O System stream model.
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Programming in Java Files and I/O Streams
Објектно орјентисано програмирање
Java’s Hierarchy Input/Output Classes and Their Purpose
Java Programming Course
תרגול מס' 5: IO (קלט-פלט) זרמי קלט וזרמי פלט ((Input & Output Streams,
Stream Oriented I/O Computer Programming II Dr. Tim Margush
OBJECT ORIENTED PROGRAMMING II LECTURE 20 GEORGE KOUTSOGIANNAKIS
Files and Streams in Java
CS 240 – Advanced Programming Concepts
David Davenport Spring 2005
Presentation transcript:

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 files Classes for serializing objects

3 Streams A stream is a sequential flow of data Streams are one-way streets. Input streams are for reading Output streams are for writing Source Program Input Stream Target Program Output Stream read write File Memory Socket

4 Streams Usage Flow: open a stream while more information Read/write information close the stream All streams are automatically opened when created.

5 Streams There are two types of streams: Byte streams for reading/writing raw bytes Character streams for reading/writing text Class Name Suffix Convention: CharacterByte ReaderInputStream Input WriterOutputStream Output

6 InputStreams abstract super-class InputStream ByteArrayInputStream FileInputStream FilterInputStream ObjectInputStream PipedInputStream SequenceInputStream DataInputStream BufferedInputStream PushbackInputStream - read from data sinks - perform some processing

7 OutputStreams abstract super-class OutputStream ByteArrayOutputStream FileOutputStream FilterOutputStream ObjectOutputStream PipedOutputStream BufferedOutputStream DataOutputStream PrintStream - write to data sinks - perform some processing

8 Readers abstract super-class Reader LineNumberReader FileReader PushbackReader BufferedReader CharArrayReader FilterReader InputStreamReader PipedReader StringReader - read from data sinks - perform some processing

9 Writers abstract super-class WriterFileWriter BufferedWriter CharArrayWriter FilterWriter OutputStreamWriter PipedWriter PrintWriter StringWriter - write to data sinks - perform some processing

10 Terminal I/O The System class provides references to the standard input, output and error streams: InputStream stdin = System.in; PrintStream stdout = System.out; PrintStream stderr = System.err;

11 is thrown in case of an error returns -1 if a normal end of stream has been reached an int with a byte information InputStream Example Reading a single byte from the standard input stream: try { int value = System.in.read();... } catch (IOException e) {... }

12 InputStream Example Another implementation: try { int value = System.in.read(); if (value != -1) { byte bValue = (byte) value; }... } catch (IOException e) {...} casting end-of- stream condition

13 Character Stream Example public static void main(String[] args) { try { FileReader in = new FileReader("in.txt"); FileWriter out = new FileWriter("out.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.close(); } catch (IOException e) { // Do something }

14 Stream Wrappers Some streams wrap others streams and add new features. A wrapper stream accepts another stream in its constructor: DataInputStream din = new DataInputStream(System.in); double d = din.readDouble(); System.in InputStream din DataInputStream readBoolean() readFloat()

InputStream Stream Wrappers (cont.) Reading a text string from the standard input: try { InputStreamReader in = new InputStreamReader(System.in); BufferedReader bin = new BufferedReader(in); String text = bin.readLine();... } catch (IOException e) {...} System.in bin in InputStreamReader BufferedReader readLine

16 The File Class A utility class for file or directory properties (name, path, permissions, etc.) Performs basic file system operations: removes a file: delete() creates a new directory: mkdir() checks if the file is writable: canWrite() creates a new file : createNewFile() No direct access to file data Use file streams for reading and writing

17 The File Class Constructors Using a full pathname: File f = new File("/doc/foo.txt"); File dir = new File("/doc/tmp"); Using a pathname relative to the current directory defined in user.dir : File f = new File(“foo.txt”); Note: Use System.getProperty(“user.dir”) to get the value of user.dir (Usually the default is the current directory of the interpreter. In Eclipse it is the project’s directory)

18 The File Class Constructors (cont) File f = new File("/doc","foo.txt"); File dir = new File("/doc"); File f = new File(dir, "foo.txt"); A File object can be created for a non- existing file or directory Use exists() to check if the file/dir exists directory pathname file name

19 The File Class Pathnames Pathnames are system-dependent "/doc/foo.txt" (UNIX format) "D:\doc\foo.txt" (Windows format) On Windows platform Java excepts path names either with '/' or '\' The system file separator is defined in: File.separator File.separatorChar

20 The File Class Directory Listing Printing all files and directories under a given directory: public static void main(String[] args) { File file = new File(args[0]); String[] files = file.list(); for (int i=0 ; i< files.length ; i++) { System.out.println(files[i]); }

21 The File Class Directory Listing (cont.) Printing all files and directories under a given directory with ".txt" suffix: public static void main(String[] args) { File file = new File(args[0]); FilenameFilter filter = new SuffixFileFilter(".txt"); String[] files = file.list(filter); for (int i=0 ; i<files.length ; i++) { System.out.println(files[i]); }

22 The File Class Directory Listing (cont.) public class SuffixFileFilter implements FilenameFilter { private String suffix; public SuffixFileFilter(String suffix) { this.suffix = suffix; } public boolean accept(File dir, String name) { return name.endsWith(suffix); }

23 The Scanner Class Breaks its input into tokens using a delimiter pattern (matches whitespace by default) The resulting tokens may then be converted into values try { Scanner s = new Scanner(System.in); int anInt = s.nextInt(); float aFloat = s.nextfloat(); String aString = s.next(); String aLine = s.nextLine(); } catch (IOException e) { // Do something }

The Scanner Class Works with any type of textual input We can change the delimiter and other options Another example: String input = "1 fish 2 fish red fish blue fish"; Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*"); System.out.println(s.nextInt()); System.out.println(s.next()); s.close(); 24 Regular expression 1 2 red blue 1 2 red blue

25 Object Serialization A mechanism that enable objects to be: saved and restored from byte streams persistent (outlive the current process) Useful for: persistent storage sending an object to a remote computer

26 Serializable Object The Default Mechanism The default mechanism includes: The Serializable interface The ObjectOutputStream The ObjectInputStream Storage/ Network ObjectOutputStream write read Serializable Object ObjectInputStream

27 The Serializable Interface Objects to be serialized must implement the java.io.Serializable interface An empty interface Most objects are Serializable : Primitives, Strings, GUI components etc. Subclasses of Serializable classes are also Serializable

28 Recursive Serialization Can we serialize a Foo object? public class Foo implements Serializable { private Bar bar; … } public class Bar {…} No, since Bar is not Serializable Solution: Implement Bar as Serializable Mark the bar field of Foo as transient Foo Bar barBar …

29 Writing Objects Writing a HashMap object ( map ) to a file*: try { FileOutputStream fileOut = new FileOutputStream("map.s"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(map); } catch (Exception e) {...} * HashMap is Serializable

30 Reading Objects try { FileInputStream fileIn = new FileInputStream("map.s"); ObjectInputStream in = new ObjectInputStream(fileIn); Map h = (Map)in.readObject(); } catch (Exception e) {...}