+ All Categories
Home > Documents > 12 io-package

12 io-package

Date post: 15-May-2015
Category:
Upload: hariprasanna-v
View: 153 times
Download: 0 times
Share this document with a friend
Description:
Hariprasanna V (9843824677)
30
Java Programming 1 Java Programming CHAPTER 20 The IO Package
Transcript
Page 1: 12 io-package

Java Programming 11

Java Programming

CHAPTER 20

The IO Package

Page 2: 12 io-package

Java Programming 22

Contents Streams Overview Byte Streams Character Streams InputStreamReader and OutputStreamWriter The Data Byte Streams Working with Files Object Serialization The IOException Classes A Taste of New I/O

Page 3: 12 io-package

Java Programming 33

The I/O Package

The java.io package defines I/O in terms of streams.

The Java.nio package and its subpackages define I/O in terms of buffers and channels. Here the “nio” is acronym of new I/O.

The java.net package provides specific support for network I/O, based around the use of sockets, with an underlying stream or channel-based model.

Page 4: 12 io-package

Java Programming 44

Streams Overview Two Major parts in the package java.io : character(16-bit

UTF-16 characters) streams and byte(8 bits) streams I/O is either text-based or data-based (binary) Input streams or output streams byte stream Readers or Writers character streams Five group of classes and interfaces in java.io

The general classes for building different types of byte and character streams.

A range of classes that define various types of streams – filtered, piped, and some specific instances of streams

The data stream classes and interfaces for reading and writing primitive values and strings.

For Interacting with files For the object serialization mechanism

Page 5: 12 io-package

Java Programming 55

Byte Streams (Binary Streams)

Object

InputStream

FileInputStream

FilterInputStreamBufferedInputStream

FilterOutputStream

FileOutputStream

BufferedOutputStream

DataInputStream

OutputStream

DataOutputStream

PrintStream

Page 6: 12 io-package

Java Programming 66

Byte Streams

InputStream

AutioInputStream

FileInputStream

ObjectInputStream

SequenceInputStream

ByteArrayInputStream

PipedInputStream

FilterInputStream

Page 7: 12 io-package

Java Programming 77

Byte Streams

OutputStream

FileOutputStream

ObjectOutputStream

ByteArrayOutputStream

PipeOutputStream

FilterOutputStream

Page 8: 12 io-package

Java Programming 88

Byte Streamsimport java.io.*;

public class CountBytes { public static void main(String[] args) throws IOException { InputStream in; if (args.length == 0) in = System.in; else in = new FileInputStream(args[0]);

int total = 0; while (in.read() != -1) total++; System.out.println(total + " bytes"); }}

The abstract class InputStream declares methods to read bytes from a particular source.

Reads a single byte of data and returns the byte that was read, as an integer in the range 0 to 255, not -128 to 127(unsigned).

Type is InputStream

Page 9: 12 io-package

Java Programming 99

Byte Streamsimport java.io.*;

public class TranslateByte { public static void main(String[] args) throws IOException { byte from = (byte) args[0].charAt(0); byte to = (byte) args[1].charAt(0); int b; while ((b = System.in.read()) != -1) System.out.write(b == from ? to : b); }}

The abstract class OutputStream provides an abstraction for writing bytes to a destination.

Run:Java TranslateByte b B

Result: (input abracadabra!)aBracadaBra!

Type is PrintStream

Page 10: 12 io-package

Java Programming 1010

Character Streams

Object

Reader

BufferedReader

InputStreamReader

FileReader

Writer OutputStreamWriter

PrintWriter

BufferedWriter

FileWriter

………

………

Page 11: 12 io-package

Java Programming 1111

Character Streams

Reader

BufferedReader

InputStreamReader

StringReader

CharArrayReader

PipedReader

FilterReader

Page 12: 12 io-package

Java Programming 1212

Character Streams

Writer

BufferedWriter

OutputStreamWriter

StringWriter

CharArrayWriter

PipedWriter

FilterWriter

PrintWriter

Page 13: 12 io-package

Java Programming 1313

Character Streamsimport java.io.*;

public class CountSpace { public static void main(String[] args) throws IOException { Reader in; if (args.length == 0) in = new InputStreamReader(System.in); else in = new FileReader(args[0]);

int ch; int total; int spaces = 0; for (total = 0; (ch = in.read()) != -1; total++) { if (Character.isWhitespace((char) ch)) spaces++; } System.out.println(total + " chars " + spaces + " spaces"); }}

The abstract classes for reading and writing streams of characters are Reader and Writer.

Run:Java CountSpace CountSpace.javaResult: 520 characters 172 spaces

The abstract class Reader provides a character stream analogous to the byte stream InputStream and the methods of Reader essentially mirror those of InputStream.

The conversion streams InputStreamReader and OutputStreamWriter translate between character and byte streams using either a specified character set encoding or the default encoding for the local system.

Page 14: 12 io-package

Java Programming 1414

Character Streams The conversion streams InputStreamR

eader and OutputStreamWriter translate between character and byte streams using either a specified character set encoding or the default encoding for the local system.

public Reader readArabic(String file) throws IOException {

InputStream fileIn = new FileInputStream(file); return new InputStreamReader(fileIn, "iso-8859-

6");} The Stream types usually have input/o

utput pairs, and most have both byte stream and character stream variants

Filter streams Buffered streams Piped streams

A group of streams, called in-memory streams: ByteArray streams CharArray streams String streams

I/O Streams that have no O/I counterpart: The Print streams LineNumberReader SequenceInputStream

Streams that are useful for building parsers Pushback streams The StreamTokenizer class

Page 15: 12 io-package

Java Programming 1515

Filter Streams

import java.io.*;

public class UppercaseConvertor extends FilterReader {

public UppercaseConvertor(Reader in) { super(in); } public int read() throws IOException { int c = super.read(); return (c==-1 ? c : Character.toUpperCase((ch

ar)c)); }

public int read(char[] buf, int offset, int count) throws IOException { int nread = super.read(buf, offset, count); int last = offset + nread; for (int i = offset; i < last; i++) buf[i] = Character.toUpperCase(buf[i]); return nread; }

public static void main(String[] args) throws IOException { StringReader src = new StringReader(args[0]); FilterReader f = new UppercaseConvertor(src); int c; while ( (c=f.read()) != -1) System.out.print((char)c); System.out.println(); }}

Run:% java UpperCaseConvertor “no lowercase”Result:NO LOWERCASE

Filter streams help to chain streams to produce composite streams of greater utility.They get their power from the ability to filter-process-what they read or write, transforming the data in some way.

abstract class

Function of the read() method was changed with filtering.

Page 16: 12 io-package

Java Programming 1616

Buffered Streams, Piped Streamsimport java.io.*;public class BufferedReaderTest { public static void main(String[] args) throws IOException { BufferedReader charStream = new BufferedReader (new InputStreamReader(S

ystem.in)); String data = charStream.readLine(); // Read a line

from standard input

System.out.println("Input = " + data); }}

The Buffered stream classes buffer their data to avoid every read or write going directly to the next stream. These classes are often used in conjunction with File streams.

import java.io.*;

class TextGenerator extends Thread { private Writer out; public TextGenerator(Writer out) { this.out = out; }

public void run() { try { try { for (char c = 'a'; c <= 'z'; c++) out.write(c); } finally { out.close(); } } catch(IOException e) { getUncaughtExceptionHandler().uncaughtException(this,

e); } }}public class Pipe { public static void main(String[] args) throws IOException { PipedWriter out = new PipedWriter(); PipedReader in = new PipedReader(out); TextGenerator data = new TextGenerator(out); data.start(); int ch; while ((ch=in.read()) != -1) System.out.print((char) ch); System.out.println(); }} Result:

abcdefghijklmnopqrstuvwxyz

InputStream Ch

ara

cte

r S

trea

m

Page 17: 12 io-package

Java Programming 1717

Print Streams, LineNumberReader The Print streams provide methods tha

t make it easy to write the values of primitive types and object to a stream, in a human-readable text format

print and println method The call out.print(f) is equivalent to

out.write(String.valueOf(f).getBytes());

LineNumberReader The LineNumberReader stream keeps

track of line numbers while reading text.

import java.io.*;

public class FindChar { public static void main(String[] args) throws IOException { if (args.length != 2) throw new IllegalArgumentException( "need char and file");

int match = args[0].charAt(0); FileReader fileIn = new FileReader(args[1]); LineNumberReader in = new LineNumberReader

(fileIn); int ch; while ((ch = in.read()) != -1) { if (ch == match) { System.out.println("'" + (char) ch + "' at line " + in.getLineNumber()); return ; } } System.out.println((char) match + " not found"); }}

Run:%java FindChar I FindChar.javaResult:‘I’ at line 4

Page 18: 12 io-package

Java Programming 1818

Pushback Streams A Pushback stream lets you

push back, or “unread” characters or bytes when you have read too far. Pushback is typically useful for breaking input into tokens.

For example, lexical scanners often know that a token (such as an identifier) has ended only when they have read the first character that follows it.

import java.io.*;

public class SequenceCount { public static void main(String[] args) throws IOException {

PushbackInputStream in = new PushbackInputStream(System.in); int max = 0; // longest sequence found int maxB = -1; // the byte in that sequence int b; // current byte in input

do { int cnt; int b1 = in.read(); for (cnt = 1; (b = in.read()) == b1; cnt++) continue; if (cnt > max) { max = cnt; // remember length maxB = b1; // remember which byte value } in.unread(b); // pushback start of ntext seq } while (b != -1); // until we hit end of input System.out.println(max + " byte of " + maxB); }}

Run and Result:% java SequenceCount12345111^D in Unix(or ^Z in Windows)3 bytes of 49

Page 19: 12 io-package

Java Programming 1919

StreamTokenzier The StreamTokenizer gives simple tokeni

zation. More general facility for scanning and converting input text is provided by the java.util.Scanner class.

Four token type TT_WORD TT_NUMBER TT_EOL TT_EOF

import java.io.*;class StreamTokenizerDemo { public static void main(String args[]) { try { FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); StreamTokenizer st = new StreamTokenizer(br); st.ordinaryChar('.'); st.wordChars('\'', '\''); while(st.nextToken() != StreamTokenizer.TT_EOF) { switch(st.ttype) { case StreamTokenizer.TT_WORD: System.out.println(st.lineno() + ") " + st.sval); break; case StreamTokenizer.TT_NUMBER: System.out.println(st.lineno() + ") " + st.nval); break; default: System.out.println(st.lineno() + ") " + (char)st.ttype); } } fr.close(); } catch (Exception e) { System.out.println("Exception: " + e); } }}

Input (tokens.txt)The price is $23.45.Is that too expensive?(I don’t think so.)

Run: java StreamTokenizerDemo tokens.txt

Result1) The1) price1) is1) $1) 23.451) .2) Is2) that2) too2) expensive2) ?3) (3) I3) don’t3) think3) so3) .3) )

Page 20: 12 io-package

Java Programming 2020

The Data Byte Streams DataInput and DataOutput These interfaces define method

s that transmit primitive types across a stream.

Read / Write methods

Read Write TypereadBoolean writeBoolean booleanreadChar writeChar charreadByte writeByte bytereadShort writeShort shortreadInt writeInt intreadLong writeLong longreadFloat writeFloat floatreadDouble writeDouble doublereadUTF writeUTF String(in U

TF format)

public static void writeData(double[] data, String file) throws IOException{ OutputStream fout = new FileOutputStream(file); DataOutputStream out = new DataOutputStream(fo

ut); out.writeInt(data.length) for(double d : data) out.writeDouble(d); out.close();}

public static double[] readData(String file) throws IOException{ InputStream fin = new FileInputStream(file); DataInputStream in = new DataInputStream(fin); double[] data = new double[in.readInt()]; for (int i = 0; i < data.length; i++) data[i] = in.readDouble(); in.close(); return data;}

Page 21: 12 io-package

Java Programming 2121

Working with Files File Streams and FileDescriptor File Streams allow you to reat a file

as a stream for input or output. A FileDescriptor object represents a

system-dependent value that describes an open file.

The RandomAccessFile class behaves like a large array of bytes stored in the file system using the file pointer.

The File class provides methods to separate pathnames into subcomponents and to ask the file system about the file a path name refers to (You can refer to the other reference).

FilenameFilter and FileFilter The FilenameFilter interface provide

s objects that filter unwanted files from a list.

import java.io.*;

public class DirFilter implements FilenameFilter {

public boolean accept(File dir, String name) { return new File(dir, name).isDirectory(); }

public static void main(String[] args) { File dir = new File(args[0]); String[] files = dir.list(new DirFilter()); System.out.println(files.length + " dir(s):"); for (String file : files) System.out.println("\t" + file); }}

Page 22: 12 io-package

Java Programming 2222

Object Serialization What is Object Serialization?

Serialization: process of converting an object’s representation into a stream of bytes

Deserialization: reconstituting an object from a byte stream

Process of reading and writing objects Writing an object is to represent its state in a s

erialized form sufficient to reconstruct the object as it is read.

Object serialization is essential to building all but the most transient applications.

Page 23: 12 io-package

Java Programming 2323

Serializing Objects How to Write to an

ObjectOutputStream Writing objects to a

stream is a straight-forward process. Example of constructing a Date object and then serializing that object:

FileOutputStream out = new FileOutputStream("theTime");

ObjectOutputStream s = new ObjectOutputStream(out);

s.writeObject("Today");

s.writeObject(new Date());s.flush();

How to Read from an ObjectOutputStream Example that reads in

the String and the Date object that was written to the file named theTime in the read example:

FileInputStream in = new FileInputStream("theTime");

ObjectInputStream s = new ObjectInputStream(in);

String today = (String)s.readObject();

Date date = (Date)s.readObject();

Page 24: 12 io-package

Java Programming 2424

Serializing Objects

Providing Object Serialization for Your Classes Implementing the Serializable Interface Customizing Serialization Implementing the Externalizable Interface Protecting Sensitive Information

[ObjectFileTest.java]/home/course/prog3/sources/week08-14/IO/objserial/ObjectFileTest.java

Page 25: 12 io-package

Java Programming 2525

The Java New I/O The Java New I/O

The new I/O (NIO) APIs introduced in v 1.4 provide new features and improved performance in the areas of buffer management, scalable network and file I/O, character-set support, and regular-expression matching. The NIO APIs supplement the I/O facilities in the java.io package.

Features Buffers for data of primitive types Character-set encoders and decoders A pattern-matching facility based on Perl-style regular expression

s Channels, a new primitive I/O abstraction A file interface that supports locks and memory mapping

Page 26: 12 io-package

Java Programming 2626

The Java New File I/O

For the New File I/O : Three Kinds of Objects are Involved

A file stream object : FileOutputStream objects, FileInputStream objects One or more buffer objects : ByteBuffer, CharBuffer, LongBuffer, etc A channel object : FileChannel,…

File Stream Object

Buffer Objects

Channel ObjectThe channel transfers data between the buffers and the file stream

Page 27: 12 io-package

Java Programming 2727

Accessing Files Channels

Channels were introduced in the 1.4 release of Java to provide a faster capability for a faster capability for input and output operations with files, network sockets, and piped I/O operations between programs than the methods provided by the stream classes.

The channel mechanism can take advantage of buffering and other capabilities of the underlying operating system and therefore is considerably more efficient than using the operations provided directly within the file stream classes.

A summary of the essential role of each of them in file operations A File object encapsulates a path to a file or a directory, and such an object enca

psulating a file path can be used to construct a file stream object. A FileInputStream object encapsulates a file that can be read by a channel. A Fil

eoutputStream object encapsulates a file that can be written by a channel. A buffer just holds data in memory. The loaded data to be written to a file will be

saved at buffer using the buffer’s put() method, and retrieved using buffer’s get() methods.

A FileChannel object can be obtained from a file stream object or a RandomAccessFile object.

Page 28: 12 io-package

Java Programming 2828

Accessing Files

The hierarchy of the channel interfaces

Page 29: 12 io-package

Java Programming 2929

Accessing Files

The Capacities of Different Buffers

Page 30: 12 io-package

Java Programming 3030

New I/O Example (ReadPrimes)import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.FileNotFoundException;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;

public class ReadPrimes { public static void main(String[] args) { File aFile = new File("primes.bin"); FileInputStream inFile = null; try { inFile = new FileInputStream(aFile);

} catch(FileNotFoundException e) { e.printStackTrace(System.err); System.exit(1); } FileChannel inChannel = inFile.getChannel(); final int PRIMECOUNT = 6; ByteBuffer buf = ByteBuffer.allocate(8*PRIMEC

OUNT); long[] primes = new long[PRIMECOUNT];

try { while(inChannel.read(buf) != -1) { ((ByteBuffer)(buf.flip())).asLongBuffer().get(pri

mes);

// List the primes read on the same line System.out.println(); for(long prime : primes) System.out.printf("%10d", prime); buf.clear(); // Clear the buffer for the

next read } System.out.println("\nEOF reached."); inFile.close(); // Close the file and the

channel } catch(IOException e) { e.printStackTrace(System.err); System.exit(1); } System.exit(0); }} You also need to read the “PrimesToFile.java”

which prints prime numbers to the file.

Channel Setup

Buffer Setup

From the channel, read data and save to the buffer


Recommended