Presented by Bartosz Sakowicz Java Input/Output (I/O)

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.
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.
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.
Chapter - 12 File and Streams (continued) This chapter includes -  DataOutputStream  DataInputStream  Object Serialization  Serializing Objects 
COMP201 Java Programming Topic 5: Input and Output Reading: Chapter 12.
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: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
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.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
פיתוח מונחה עצמים – שפת JAVA קבצים. References קורס "שיטות בהנדסת תוכנה", הפקולטה למדעי המחשב, הטכניון. קורס "מערכות מידע מבוזרות", הפקולטה להנדסת תעשייה.
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.
Files and Streams. Java I/O File I/O I/O streams provide data input/output solutions to the programs. A stream can represent many different kinds of sources.
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.
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: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
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.
Object Persistence and Object serialization CSNB534 Asma Shakil.
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.
Java Input/Output CSE301 University of Sunderland Harry Erwin, PhD Half Lecture.
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.
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.
1 CISC 370: I/O Streams James Atlas June 24, 2008.
– Advanced Programming P ROGRAMMING IN Lecture 22 Input and Output System.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
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.
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.
Chapter - 11 Introduction to File and Streams This chapter includes -  Defining a File  Testing and Checking File Objects  Accessing File Objects.
DEPARTMENT OF COMPUTER SCIENCE N.HARIKA. Contents Overview of I/O Streams Character Streams Byte Streams Using the Streams 2.
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 Programming: Advanced Topics 1 Input/Output and Serialization.
Java Programming Language (3) - Input/Output Stream –
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
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
Exception Handling, Reading and Writing in Files, Serialization,
OO Design and Programming II I/O: Reading and Writing
Ch14 Files and Streams OBJECTIVES
Chapter 17 Binary I/O.
Object Writing in files
12: The Java I/O System stream model.
I/O Basics.
Chapter 17 Binary I/O 1.
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Files and Streams in Java
Presentation transcript:

Presented by Bartosz Sakowicz Java Input/Output (I/O)

Overview of I/O streams To bring in information, a program opens a stream on an information source (a file, memory, a socket) and reads the information sequentially: Similarly, a program can send information to an external destination by opening a stream to a destination and writing the information out sequentially:

Overview of I/O streams(2) The algorithms for sequentially reading and writing data are basically the same: Presented by Bartosz Sakowicz DMCS TUL Writing open a stream while more information write information close the stream Reading open a stream while more information read information close the stream The java.io package contains a collection of stream classes that support these algorithms for reading and writing. To use these classes, a program needs to import the java.io package.java.io java.io

Character streams The stream classes are divided into two class hierarchies, based on the data type (either characters or bytes) on which they operate. Reader Reader and Writer are the abstract superclasses for character streams in java.io. Reader provides the API and partial implementation for readers--streams that read 16-bit characters-- and Writer provides the API and partial implementation for writers- -streams that write 16-bit characters.Writer Most programs should use readers and writers to read and write textual information. The reason is that they can handle any character in the Unicode character set, whereas the byte streams are limited to ISO-Latin-1 8-bit bytes. Presented by Bartosz Sakowicz DMCS TUL

Character streams(2)

Byte streams Presented by Bartosz Sakowicz DMCS TUL To read and write 8-bit bytes, programs should use the byte streams, descendants of InputStream and OutputStream.InputStream OutputStream InputStream and OutputStream provide the API and partial implementation for input streams (streams that read 8-bit bytes) and output streams (streams that write 8-bit bytes). These streams are typically used to read and write binary data such as images and sounds. Two of the byte stream classes, ObjectInputStream and ObjectOutputStream, are used for object serialization.

Byte streams(2)

The I/O superclasses Reader and InputStream define similar APIs but for different data types. For example, Reader contains these methods for reading characters and arrays of characters: int read() int read(char cbuf[]) int read(char cbuf[], int offset, int length) InputStream defines the same methods but for reading bytes and arrays of bytes: int read() int read(byte cbuf[]) int read(byte cbuf[], int offset, int length) Both streams provide methods for marking a location in the stream, skipping input, and resetting the current position.

The I/O superclasses (2) Writer and OutputStream are similarly parallel. Writer defines these methods for writing characters and arrays of characters: int write(int c) int write(char cbuf[]) int write(char cbuf[], int offset, int length) And OutputStream defines the same methods but for bytes: int write(int c) int write(byte cbuf[]) int write(byte cbuf[], int offset, int length) All of the streams are automatically opened when created. You can close any stream explicitly by calling its close method or the garbage collector can implicitly close it, which occurs when the object is no longer referenced.

I/O streams – memory Presented by Bartosz Sakowicz DMCS TUL CharArrayReader CharArrayWriter ByteArrayInputStream ByteArrayOutputStream Use these streams to read from and write to memory. You create these streams on an existing array and then use the read and write methods to read from or write to the array. StringReader StringWriter StringBufferInputStream Use StringReader to read characters from a String in memory. Use StringWriter to write to a String. StringWriter collects the characters written to it in a StringBuffer, which can then be converted to a String. StringBufferInputStream is similar to StringReader, except that it reads bytes from a StringBuffer.

I/O streams - pipe and file Presented by Bartosz Sakowicz DMCS TUL PipedReaderPipedWriter PipedInputStreamPipedOutputStream Implement the input and output components of a pipe. Pipes are used to channel the output from one thread into the input of another. FileReaderFileWriter FileInputStreamFileOutputStream Collectively called file streams, these streams are used to read from or write to a file on the native file system.

I/O streams - concatenation and serialization Presented by Bartosz Sakowicz DMCS TUL SequenceInputStream Concatenates multiple input streams into one input stream. ObjectInputStream ObjectOutputStream Used to serialize objects.

I/O streams - counting and peeking ahead Presented by Bartosz Sakowicz DMCS TUL LineNumberReaderLineNumberInputStream Keeps track of line numbers while reading. PushbackReaderPushbackInputStream These input streams each have a pushback buffer. When reading data from a stream, it is sometimes useful to peek at the next few bytes or characters in the stream to decide what to do next.

I/O streams - printing and buffering Presented by Bartosz Sakowicz DMCS TUL PrintWriterPrintStream Contain convenient printing methods. These are the easiest streams to write to, so you will often see other writable streams wrapped in one of these. BufferedReaderBufferedWriter BufferedInputStreamBufferedOutputStream Buffer data while reading or writing, thereby reducing the number of accesses required on the original data source. Buffered streams are typically more efficient than similar nonbuffered streams and are often used with other streams.

I/O streams - filtering Presented by Bartosz Sakowicz DMCS TUL FilterReaderFilterWriter FilterInputStreamFilterOutputStream These abstract classes define the interface for filter streams, which filter data as it's being read or written.

I/O streams - converting betweeng bytes and characters Presented by Bartosz Sakowicz DMCS TUL InputStreamReaderOutputStreamWriter A reader and writer pair that forms the bridge between byte streams and character streams. An InputStreamReader reads bytes from an InputStream and converts them to characters, using the default character encoding or a character encoding specified by name. An OutputStreamWriter converts characters to bytes, using the default character encoding or a character encoding specified by name and then writes those bytes to an OutputStream. You can get the name of the default character encoding by calling System.getProperty("file.encoding").

Using file streams Presented by Bartosz Sakowicz DMCS TUL import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("in.txt"); File outputFile = new File("out.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } //copying bytes by analogy

Concatenating files Presented by Bartosz Sakowicz DMCS TUL import java.io.*; public class Concatenate { public static void main(String[] args) throws IOException { ListOfFiles mylist = new ListOfFiles(args); SequenceInputStream s = new SequenceInputStream(mylist); int c; while ((c = s.read()) != -1) System.out.write(c); s.close(); } } //ListOfFiles implements Enumeration. // nextElement() returns FileInputStream

Using filtering streams Presented by Bartosz Sakowicz DMCS TUL The java.io package provides a set of abstract classes that define and partially implement filter streams. A filter stream filters data as it's being read from or written to the stream. A filter stream is constructed on another stream (the underlying stream). The read method in a readable filter stream reads input from the underlying stream, filters it, and passes on the filtered data to the caller. The write method in a writable filter stream filters the data and then writes it to the underlying stream. The filtering done by the streams depends on the stream. Some streams buffer the data, some count data as it goes by, and others convert data to another form.

DataInputStream and DataOutputStream example Presented by Bartosz Sakowicz DMCS TUL public class DataIODemo { public static void main(String[] args) throws IOException { DataOutputStream out = new DataOutputStream(new FileOutputStream("invoice1.txt")); double[] prices = { 19.99, 9.99, }; int[] units = { 12, 8, 13}; String[] descs = { "Java T-shirt", "Java Mug", "Java Pin" };

Data... example(2) Presented by Bartosz Sakowicz DMCS TUL for (int i = 0; i < prices.length; i ++) { out.writeDouble(prices[i]); out.writeChar('\t'); out.writeInt(units[i]); out.writeChar('\t'); out.writeChars(descs[i]); out.writeChar('\n'); } out.close(); /* In the invoice1.txt should be: Java T-shirt Java Mug Java Pin */

Data... example(3) Presented by Bartosz Sakowicz DMCS TUL // read it in again DataInputStream in = new DataInputStream(new FileInputStream("invoice1.txt")); double price; int unit; StringBuffer desc; double total = 0.0;

Data... example(4) Presented by Bartosz Sakowicz DMCS TUL try { while (true) { price = in.readDouble(); in.readChar(); // throws out the tab unit = in.readInt(); in.readChar(); // throws out the tab char chr; desc = new StringBuffer(20); char lineSep = System.getProperty("line.separator").charAt(0);

Data... example(5) Presented by Bartosz Sakowicz DMCS TUL while ((chr = in.readChar()) != lineSep) desc.append(chr); System.out.println("You've ordered " + unit + " units of " + desc + " at $" + price); total = total + unit * price; } } catch (EOFException e) { } System.out.println("For a TOTAL of: $" + total); in.close(); }}

Data... example(6) Presented by Bartosz Sakowicz DMCS TUL The output should be: You've ordered 12 units of Java T-shirt at $19.99 You've ordered 8 units of Java Mug at $9.99 You've ordered 13 units of Duke Juggling Dolls at $15.99 For a TOTAL of: $500,97

Writing filtering streams Presented by Bartosz Sakowicz DMCS TUL 1.Create a subclass of FilterInputStream and FilterOutputStream. Input and output streams often come in pairs, so it's likely that you will need to create both input and output versions of your filter stream. 2.Override the read and write methods, if you need to. 3.Provide any new methods. 4.Make sure that the input and output streams work together.

Object serialization Presented by Bartosz Sakowicz DMCS TUL Reading and writing objects is a process called object serialization.The key to writing an object is to represent its state in a serialized form sufficient to reconstruct the object as it is read. Object serialization is essential to building all but the most transient applications. You can use object serialization in the following ways: Remote Method Invocation (RMI) - communication between objects via sockets Lightweight persistence - the archival of an object for use in a later invocation of the same program.

Writing to an ObjectOutputStream Presented by Bartosz Sakowicz DMCS TUL Example: FileOutputStream out = new FileOutputStream("theTime"); ObjectOutputStream s = new ObjectOutputStream(out); s.writeObject("Today"); s.writeObject(new Date()); s.flush();

Writing to an ObjectOutputStream(2) Presented by Bartosz Sakowicz DMCS TUL ObjectOutputStream must be constructed on another stream. ObjectOutputStream implements the DataOutput interface that defines many methods for writing primitive data types, such as writeInt, writeFloat, or writeUTF. The writeObject method throws a NotSerializableException if it's given an object that is not serializable. An object is serializable only if its class implements the Serializable interface.

Reading from ObjectInputStream Presented by Bartosz Sakowicz DMCS TUL Once you've written objects and primitive data types to a stream, you can read them out again and reconstruct the objects: FileInputStream in = new FileInputStream("theTime"); ObjectInputStream s = new ObjectInputStream(in); String today = (String)s.readObject(); Date date = (Date)s.readObject();

Reading from ObjectInputStream(2) Presented by Bartosz Sakowicz DMCS TUL ObjectInputStream must be constructed on another stream. In previous example, the objects were archived in a file, so the code constructs an ObjectInputStream on a FileInputStream. Next, the code uses ObjectInputStream's readObject method to read the String and the Date objects from the file. The objects must be read from the stream in the same order in which they were written. The return value from readObject is an object that is cast to and assigned to a specific type. ObjectInputStream stream implements the DataInput interface that defines methods for reading primitive data types (analogous to DataOutput Interface).

Providing serialization for a class Presented by Bartosz Sakowicz DMCS TUL Complete definition of the Serializable interface: package java.io; public interface Serializable { }; Making instances of your classes serializable is: public class MyClass implements Serializable {... }

Providing serialization for a class(2) Presented by Bartosz Sakowicz DMCS TUL You don't have to write any methods. The serialization of instances of this class are handled by the defaultWriteObject method of ObjectOutputStream. This method automatically writes out everything required to reconstruct an instance of the class, including the following: Class of the object Class signature Values of all non-transient and non-static members, including members that refer to other objects You can deserialize any instance of the class with the defaultReadObject method in ObjectInputStream. For many classes, this default behavior is good enough.

Customing serialization Presented by Bartosz Sakowicz DMCS TUL You can customize serialization for your classes by providing two methods for it: writeObject and readObject. The writeObject method controls what information is saved and is typically used to append additional information to the stream. The readObject method either reads the information written by the corresponding writeObject method or can be used to update the state of the object after it has been restored.

Customing serialization(2) Presented by Bartosz Sakowicz DMCS TUL The writeObject and readObject methods must be declared exactly as shown: private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); // customized serialization code } The readObject method must read in everything written by writeObject in the same order in which it was written: private void readObject(ObjectInputStream s) throws IOException { s.defaultReadObject(); // customized deserialization code }

File and StreamTokenizer Presented by Bartosz Sakowicz DMCS TUL File class Represents a file on the native file system. You can create a File object for a file on the native file system and then query the object for information about that file, such as its full path name. StreamTokenizer class (up to jdk 1.5) Breaks the contents of a stream into tokens. Tokens are the smallest unit recognized by a text-parsing algorithm (such as words, symbols, and so on). A StreamTokenizer object can be used to parse any text file. For example, you could use it to parse a source file into variable names, operators, and so on, or to parse an HTML file into HTML tags. Similar class is StringTokenizer, Scanner.

New Input/Output Presented by Bartosz Sakowicz DMCS TUL The New I/O (NIO) API introduced in JDK 1.4 provides a completely new model of low-level I/O. Unlike the original I/O libraries in the java.io package, which were strongly stream-oriented, the New I/O API in the java.nio package is block-oriented. This means that I/O operations, wherever possible, are performed on large blocks of data in a single step, rather than on one byte or character at a time. Channels and buffers represent the two basic abstractions within the New I/O API.

Channels Presented by Bartosz Sakowicz DMCS TUL Channels correspond roughly to input and output streams: they are sources and sinks for sequential data. However, whereas input and output streams deal most directly with single bytes, channels read and write data in chunks. Additionally, a channel can be bidirectional, in which case it corresponds to both an input stream and an output stream.

Buffers Presented by Bartosz Sakowicz DMCS TUL The chunks of data that are written to and read from channels are contained in objects called buffers. A buffer is an array of data enclosed in an abstraction that makes reading from, and writing to, channels easy and convenient.

Copying files example Presented by Bartosz Sakowicz DMCS TUL import java.io.*; import java.nio.*; import java.nio.channels.*; public class CopyFile { static public void main( String args[] ) throws Exception { String infile = args[0], outfile = args[1]; FileInputStream fin = new FileInputStream( infile ); FileOutputStream fout = new FileOutputStream( outfile );

Copying files example(2) Presented by Bartosz Sakowicz DMCS TUL FileChannel inc = fin.getChannel(); FileChannel outc = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate( 1024 ); while (true) { int ret = inc.read( buffer ); if (ret==-1) // nothing left to read break; buffer.flip();// prepare buffer to reading outc.write( buffer ); buffer.clear(); // Make room for the next read } } }

NIO.2 in JDK 1.7 Path class File operations Directory operations Hard links/symbolic links Privilleges Finding files (rules similar to regex possibilities)