Java Input/Output. Reading standard input Surprisingly complicated (GUI focus) Old-fashioned way: BufferedReader r = new BufferedReader(new InputStreamReader(System.in));

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 3. 2 Handling Primitive Data Types The basic input and output streams provide read/write methods that can be used.
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.
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.
III. Streams. Introduction Often a program needs to bring in information from an external source or to send out information to an external destination.
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.
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.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
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.
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.
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 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.
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,
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.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
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.
Introduction to Computation and Problem Solving Class 29: Introduction to Streams Prof. Steven R. Lerman and Dr. V. Judson Harward.
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.
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 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
Company Input/Output Stream –. Input/Output Stream Data Program Input Stream Output Stream.
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.
Exception Handling, Reading and Writing in Files, Serialization, Exceptions, Files, Streams, File Readers and Writers, Serializable SoftUni Team Technical.
I/O Basics Java does provide strong, flexible support for I/O related to files and networks. Java’s console based interaction is limited since in real.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
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 Programming: Advanced Topics 1 Input/Output and Serialization.
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.
Chapter 10: I/O Streams Input Streams Output Streams
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
Exception Handling, Reading and Writing in Files, Serialization,
Chapter 17 Binary I/O.
Object Writing in files
I/O Basics.
Chapter 17 Binary I/O 1.
Accessing Files in Java
File.
Programming in Java Files and I/O Streams
Files and Streams in Java
CS 240 – Advanced Programming Concepts
David Davenport Spring 2005
Presentation transcript:

Java Input/Output

Reading standard input Surprisingly complicated (GUI focus) Old-fashioned way: BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); String line = null; while ((line = r.readLine()) != null) { // process line … }

Two modern ways Scanner s = new Scanner(System.in); while (s.hasNextLine()) { String line = s.nextLine(); // process line … } Console r = System.console(); String line = null; while ((line = r.readLine()) != null) { // process line … }

Utility methods for Strings “the quick brown fox”.split(“ ”); => {“the”,“quick”,”brown”,”fox”} String.valueOf(13) => “13” String.valueOf(x) => x.toString() Integer.parseInt(“37”) => 37 (int) new Integer(“37”) => 37 (Integer object) similar for other primitives types …

RandomAccessFile makes files available “like a big array of bytes”, allows random read/write access anywhere inside a file only supports primitive types + Strings new RandomAccessFile(String fileName, String mode), where mode is “r”,”rw”,”rws”,”rwd” void seek(long pos) long getFilePointer() double readDouble() and similar long length() void setLength(long newLength)

RandomAccessFile example RandomAccessFile rf = new RandomAccessFile(“doubles”,”rw”); // read third double: go to 2 * 8 (size of one) rf.seek(8*2); double x = rf.readDouble(); // overwrite first double value rf.seek(0); rf.writeDouble(x); rf.close();

Streams vs. Readers/Writers Confusing number of alternatives: –Streams: for binary 8bit (byte) quantities –Readers/Writers: for String and 16bit Unicode characters Streams: always 8bit quantities at the lowest level, but may provide higher-level abstractions as well, e.g. –readInt() [in class DataInputStream] will process four 8bit values to read a single 32bit int value

InputStream hierarchy InputStream ByteArray File Filter Piped Object Sequence InputStream InputStream InputStream Data Buffered LineNumber PushBack InputStream InputStream InputStream InputStream Physical: ByteArrayInputStream, FileInputStream, PipedInputStream Virtual: all others

Class InputStream abstract class InputStream { int read() throws IOException; int read(byte[] buffer) throws IOException; long skip(long n) throws IOException; int available() throws IOException; void close() throws IOException; } IOException: e.g. file cannot be opened, read operation was interrupted, …

Physical input streams Some constructors: –ByteArrayInputStream(byte[] buffer); –ByteArrayInputStream(byte[] buffer, int offset, int count) –FileInputStream(File f); –FileInputStream(String fileName); –PipedInputStream(PipedOutputStream p); Why use File instead of String as argument to the FileInputStream constructor?

Virtual input streams Build on top of physical ones using composition, add additional behaviour, e.g.: –SequenceInputStream: appends a couple of InputStreams giving the impression/illusion of just a single stream –FilterInputStream: an instance of the “Wrapper design pattern” Client read() Filter read() InputStream

DataInputStream class DataInputStream extends FilterInputStream implements DataInput { … public boolean readBoolean() throws IOException public byte readByte() throws IOException public char readChar() throws IOException public double readDouble() throws IOException public int readInt() throws IOException public long readLong() throws IOException public short readShort() throws IOException public int readUnsignedByte() throws IOException public int readUnsignedShort() throws IOException } Read bytes (binary representation, not textual), return them as primitive data types Possibly generated by DataOutputStream Same interface also used by RandomAccessFile

Stream Tokenizer Useful to break up text into tokens (words, numbers, others): public class TokenTest { public static void main(String[] args) { StreamTokenizer tok = new StreamTokenizer(System.in); try { while (tok.nextToken() != tok.TT_EOF) { switch(tok.ttype) { case tok.TT_NUMBER: System.out.println(“number “ + tok.val); break; … case default: … }} } catch (IOException e) {} }} “23-skidoo, kid!” yields: number 23.0 token – word skidoo …

Output stream hierachy OutputStream ByteArray File Filter Piped Object OutputStream OutputStream OutputStream OutputStream OutputStream Data Buffered PrintStream OutputStream OutputStream Similar to InputStream hierarchy: physical: ByteArrayOutputStream, FileOutputStream, PipedOutputStream virtual: all others

OutputStream public abstract class OutputStream { public abstract void write(int b) throws IOException public void write(byte[] buffer) throws IOException public void flush() throws IOException public void close() throws IOException } Quite a few output streams use buffering (for efficiency reasons), flush() explicitly forces completion of pending output operations

PrintStream public class PrintStream extends FilterOutputStream { … public void print(boolean bool) public void print(int inum) public void print(float fnum) public void print(double dnum) public void print(String str) public void print(Object o) { print(o.toString()); } … } Generates textual representations print(Object o) is purely polymorphic

Object Serialization Transform instances into 8bit units can be send over networks, stored in filesystems Allows for object persistence, i.e. save state across program invocations Interface Serializable, classes ObjectInputStream and ObjectOutputStream Would be tricky: need to get shared structure right!

Object Serialization example import java.io.Serializable; class Pair implements Serializable { public Object first; public Object second; } class Holder implements Serializable { public Object value; } Actually empty interface, so “implements Serializable” suffices

Object Serialization example contd. import java.util.Date; … Date today = new Date(); Holder a = new Holder(); a.value = today; Holder b = new Holder(); b.value = today; Pair c = new Pair(); c.first = a; c.second = b; c a b today

Object Serialization: write to file try { FileOutputStream f = new FileOutputStream(“saveState”); ObjectOutputStream s = new ObjectOutputStream(f); s.writeObject(“The value of c is”); s.writeObject(c); s.flush(); } catch (IOException e) System.out.println(“received error “ + e); }

Object Serialization: read back try { FileInputStream f = new FileInputStream(“saveState”); ObjectInputStream s = new ObjectInputStream(f); String tag = (String) s.readObject(); Pair c = (Pair) s.readObject(); } catch (IOException e) { System.out.println(“received IO exception “ + e); } catch (ClassNotFoundException e) { System.out.println(“received class exception “ + e); }

Object Serialization: check == … Holder a = (Holder) c.first; Holder b = (Holder) c.second; if( a.value == b.value ) System.out.println(“it’s the same object”); …

Piped IO Producer/consumer paradigm Multiple threads and pipes A pipe: buffered data area used for both reading and writing May suspend on IO operations: –Read, because empty –Write, because full In Java: matched pair of streams: PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(in);

Piped IO Example: Fibonacci + Prime class FibMaker extends Thread { private DataOutputStream out; public FibMaker(DataOutputStream o) {out = o;} public void run() { int n = 0; int m = 1; try { out.writeInt(m); while(m<100000) { int newValue = n+m; n=m; m=newValue; out.writeInt(newValue); } out.close(); } catch (IOException e) {return; }}}

Piped IO Example contd. class PipeTest { static public void main(String[] args) {PipeTest w = new PipeTest(); w.show(System.out);} private PipeTest(PrintStream out) { DataInputStream fibs = makeFibs(); DataInputStream primes = makePrimes(); try { int x = fibs.readInt(); int y = primes.readInt(); while (x < ) { if (x == y) { out.println(x + “ is both prime and fib”); x = fibs.readInt(); y = primes.readInt(); } else if (x<y) x = fibs.readInt(); else y = primes.readInt(); } } catch (IOException e) { System.exit(0);}}

Piped IO Example contd. private DataInputStream makeFibs() { try { PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(in); Thread fibThread = new FibMaker (new DataOutputStream(out)); fibThread.start(); return new DataInputStream(in); } catch (IOException e) { return null;} }

Readers and Writers hierarchy Reader Buffered CharArray InputStream Filter Piped String Reader Reader Reader LineNumber File Pushback Reader Reader Reader Writer Buffered CharArray OutputStream Filter Piped Print String Writer Writer Writer Writer Writer Writer Writer FileWriter

Readers/Writers Purely textual, but similar to IO streams try { FileReader f = new FileReader(“filename”); BufferedReader b = new BufferedReader(b); … } catch (…){ … } … Also wrap around IO streams: FileInputStream f = new FileInputStream(“f”); InputStreamReader r = new InputStreamReader(f, “MacCyrillic”); BufferedReader b = new BufferedReader(r); String text = r.readLine();

String.split(String Regex) even simpler than StreamTokenizer "boo:and:foo”.split(“:”) -> {“boo”,”and”,”foo”} "boo:and:foo”.split(“o”) -> {“b”,””,”:and:f”} Typical loop to process file input: BufferedReader reader = new BufferedReader( new FileReader(fileName)); String line = null; while ((line = reader.readLine()) != null) { String[] tokens = line.split(“ “); // process tokens … }