Programming in Java Java...
Transcript of Programming in Java Java...
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Streams
Programming in Java
Java Streams
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Streams
Streams Concept:
A stream is a flow of data:� characters, numbers, bytes
(the interpretation depends on the program that does
the reading or writing)
� files are considered streams of bits or bytes:
• associated with an object
• binary file: sequence of binary digits (bits)
• text files: sequence of characters (ASCII, UTF8)
• file ends with: end-of-file marker or specific byte number
� devices associated with streams:• System.in, System.out, System.err
ASCII: American Standard Code for Information Interchange
UTF: Unicode Text Format
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Streams: Standard I/O Streams
C library concept:
Standard input and output streams
System.errStandard err:
System.outStandard output:
System.inStandard input:
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Streams (package java.io)
Java
Program
Input Stream Output Stream
Input Stream:
� data flows into the program
Output Stream:
� data flows out of the program
Java classes for file processing:package java.io
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Streams (package java.io)
• Sources/Destinations for I/O
Files: ���� File
Strings: ���� String, StringBuffer
Buffer: ���� CharArray, ByteArray
Programs: ���� Pipe
• Type of I/O
buffered: ���� Buffered
filtered: ���� Filter
line by line: ���� LineNumber
printer: ���� Print
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Streams (package java.io)
• Streams for Unicode I/O (type char, 16 Bit)(since JDK 1.1)
Classes for input: Reader
Classes for output: Writer
• Streams for Byte I/O (type byte, 8 Bit)
Classes for input: InputStream
Classes for output: OutputStream
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Streams (package java.io)
Java
Program
Input Stream Output Stream
Reader (char)
InputStream (byte)
Writer (char)
OutputStream (byte)
PrintStreamByteArray
PrintWriterCharArray
LineNumberInputStreamPipe
LineNumberReaderFile
FilterStringBuffer
BufferedString
I/O TypeSource/Destination
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Hierarchy For Package java.io
java.lang.Object
File
FileDescriptor
InputStream Abstract Classes
ByteArrayInputStream
FileInputStream
FilterInputStream
BufferedInputStream
DataInputStream
LineNumberInputStream
PushbackInputStream
ObjectInputStream
PipedInputStream
SequenceInputStream
StringBufferInputStream
OutputStream
ByteArrayOutputStream
FileOutputStream
FilterOutputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectOutputStream
PipedOutputStream
Streams and Files
incomplete
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Output Stream
public abstract class OutputStream
extends Object
� Superclass of all classes representing an output stream
of bytes
� Subclasses of OutputStream must provide at least a
method to write one byte of output.
� Possible subclass: FileOutputStream
- Output Stream for writing data to a File (raw bytes, e.g.
image data)
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Input Stream
public abstract class InputStream
extends Object
� Superclass of all classes representing an Input stream
of bytes
� Subclasses of InputStream must provide at least a
method that returns the next byte of input.
� Possible subclass: FileInputStream
- Input Stream for reading data to a file in a file system
(raw bytes, e.g. image data)
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Streams (package java.io)
Output in character arrayCharArrayWriter
String outputStringWriter
Output in PipedReaderPipedWriter
Output bufferingBufferedWriter
Text output of basic typesPrintWriter
Abstract base class to construct output filtersFilterWriter
File outputFileWriter
abstract base class (bridge from character streams to byte streams)
OutputStreamWriter
I/O TypeClass
Writer is an abstract class and cannot be instantiated;
Several classes exist that are derived from Writer
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Streams (package java.io)
import java.io.*;
public class IOTest{
public static void main(String[] args){
String hello = "Hallo JAVA\r\n";FileWriter f1;
try {f1 = new FileWriter("hello.txt");f1.write(hello);f1.close();
} catch (IOException e) {System.out.println("Error");
}}
} Java
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Streams (package java.io)
Simple Input and Output StreamsOverview of the nonabstract classes that subclass directly from InputStream and OutputStream:
FileInputStream and FileOutputStream
Read data from or write data to a file on the native file system.
PipedInputStream and PipedOutputStream
Implement the input and output components of a pipe.
ByteArrayInputStream and ByteArrayOutputStream
Read data from or write data to a byte array in memory.
SequenceInputStream
Concatenate multiple input streams into one input stream.
StringBufferInputStream
Allow programs to read from a StringBuffer as if it were an input stream.
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
File/Stream Operations
restart at beginning, reset()restart
methodsprint(), println(), write(), writeln()
output
methods read(), readln()input
method close() of stream classclose
done by stream object constructoropen
DescriptionOperation
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
File/Stream Exceptions
Superclass: IOException
DescriptionException
A malformed UTF-8 string has been read UTFDataFormatException
An end of file or end of stream has been
reached unexpectedly during input EOFException
An I/O operation has been interrupted InterruptedIOException
The attempt to open the file denoted by a
specified pathname has failed. FileNotFoundException
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.io.IOException
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
stdio Streams
Provided by the operating system there are three streams
already opended in Java programs (java.lang.System):
� standard input (stdin) ���� System.in
� standard output (stdout) ���� System.out
� standard error (stderr) ���� System.err
By default these streams are connected to the console:
� keyboard and screen
stdinstdout
stderr
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Standard Output
class System {
public static PrintStream out;
� Methods: write(), close(), flush()
� Text output:
9-10 versions of print(), println() taking parameters
of different type:
- char, char(), String (upper byte of each Unicode
character is ignored)
- boolean, int, long, float, double, Object
(automatic translation to text)
� methods do not throw IOException
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Writing to a File
FileOutputStream
Methods:
� write(int b)
Writes the specified byte to this file output stream.
� write(byte[] b)
Writes b.length bytes from the specified byte array to this file output
stream.
� write(byte[] b, int off, int len)
Writes len bytes from the specified byte array starting at offset off to
this file output stream.
� close()
closes this file output stream and releases any system resources
associated with this stream.
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Reading a File
FileInputStream
Methods:� int read()
Reads a byte of data from this input stream.
� int read(byte[] b)Reads up to b.lengthb.lengthb.lengthb.length bytes of data from this input stream into an array of
bytes.
� int read(byte[] b, int off, int len) Reads up to len bytes of data from this input stream into an array of
bytes.
� long skip(long n)Skips over and discards nnnn bytes of data from the input stream.
� void close()loses this file output stream and releases any system resources
associated with this stream.
� int available()Returns the number of bytes that can be read from this file input stream
without blocking.
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Streams
Programming in Java
Java Streams – Plug Together
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Java Stream Architecture
Very flexible "Plug together" architecture
stdin
filter object
stream object
storage
(file)
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Buffered File Output
import java.io.*;
public class IOTest01{
public static void main(String args[]){
Writer f1;BufferedWriter f2;String s;
try {f1 = new FileWriter("buffer.txt");f2 = new BufferedWriter(f1);for (int i = 1; i <= 10000; ++i) {
s = "This is line No. " + i;f2.write(s);f2.newLine();
}f2.close();f1.close();
} catch (IOException e) {System.out.println("Error");
}}
} Java
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Cascading Constructors
BufferedWriter f;
String s;
try {
f = new BufferedWriter(
new FileWriter("buffer.txt"));
for (int i = 1; i <= 10000; ++i) {
s = "This is line No. " + i";
f.write(s);
f.newLine();
}
f.close();
Cascading Writer Constructors
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Writing to a Text File
Create a PrintWriter object connected to a
FileOutputStream (or FileWriter) object
PrintWriter myOutput;
try
{
FileOutputStream fos = new FileOutputStream ("test.txt");
myOutput = new PrintWriter(fos, true);
. . .}
catch (IOException e)
{
System.err.println(e);
}
name of new file
true:
auto flush on println
e.g. illegal name, no
write permission
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Writing to a Text File
PrintWriter myOutput FileOutputStream fos
test.txt
Write data using print(), println():
myOutput.println("Name: " + name);
myOutput.println();
Finish up:myOutput.close();
no
IOExceptions
thrown
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Reading a Text File
Create a BufferedReader object connected to a
FileReader object
BufferedReader myInput;
try
{
FileReader fr = new FileReader ("test.txt");
myInput = new BufferedReader(fr);
. . .}
catch (IOException e)
{
System.err.println(e);
}
name of existing file
e.g. illegal name, no read
permission, file not found
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Reading a Text File
BufferedReader myInput FileReader fr
test.txt
Note:The creation of myInput could be written in one statement:
myInput = new BufferedReader(new FileReader ("test.txt"));
object can be changed, e.g. in
order to read from a network
calling
objects
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Reading a Text File
import java.io.*; /** display text file with line numbers. */class ReadFile {
public static void main(String[] args) {
BufferedReader myInput;String line;int lineNum=0;try{
FileReader fr = new FileReader ("test.java");myInput = new BufferedReader(fr);line = myInput.readLine();while (line != null){
lineNum++;System.out.println (lineNum + " " + line);line = myInput.readLine();
}myInput.close();
}catch (IOException e){
System.err.println(e);}System.out.println("End");
}}
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Data Input / Output
public class DataInputStream
extends FilterInputStream
� A data input stream lets an application read primitive Java
data types from an underlying input stream in a machine-
independent way. An application uses a data output stream
to write data that can later be read by a data input stream.
public class DataOutputStream
extends FilterOutputStream
� A data output stream lets an application write primitive Java
data types to an output stream in a portable way. An
application can then use a data input stream to read the data
back in.
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Writing to a Binary File
DataOutputStream myOutput FileOutputStream fos
btest.dat
Write data using various forms of write() provided by
DataOutputStream:
try {
myOutput = new DataOutputStream(new FileOutputStream("btest.dat"));
. . .
myOutput.writeUTF(name);
myOutput.writeChar(…);
myOutput.writeInt(…);
myOutput.writeDouble(…);
myOutput.flush();
myOutput.close();
} catch (IOException e) {. . .}
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Reading a Binary File
DataInputStream myInput FileInputStream fis
btest.dat
Read data using various forms of read() provided by
DataInputStream:
try {
myInput = new DataInputStream(new FileInputStream("btest.dat"));
. . .
name = myInput.readUTF();
x = myInput.readChar(…);
i = myInput.readInt(…);
d = myInput.readDouble(…);
myInput.close();
} catch (IOException e) {. . .}
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Keyboard Input
public class InputStreamReader
extends Reader
import java.io.*;
public class KeyboardInput {
public static void main (String [] args) {
BufferedReader myInput = new BufferedReader(
new InputStreamReader(System.in));
String line;
try {
line = myInput.readLine();
}
catch (IOException e) {. . .}
System.out.println(line);
}
}
Standard Input
BufferedReader expects
instance of Reader
Java
Bridge from byte streams
to character streams
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Keyboard Input - DataInputStream
DataInputStream din =
new DataInputStream (System.in);
s=din.readLine();
inpublic static final InputStream in
The "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.
System - class java.lang.System.The System class contains several useful class fields and methods.
public DataInputStream(InputStream in)
Creates a FilterInputStream and saves its argument, the input stream in, for later use.Parameters: in - the input stream.
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Keyboard Input - DataInputStream
import java.io.*;
class testdata
{
public static void main(String args[]) throws java.io.IOException
{
double tmp;
String s;
DataInputStream din = new DataInputStream (System.in);
s=din.readLine();
tmp = Double.valueOf(s).doubleValue();
System.out.println("Ergebnis " + tmp); // new line
}
}
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Keyboard Input - DataInputStream
import java.io.*;
class testdata2
{
public static void main(String args[]) throws java.io.IOException
{
double tmp;
String s;
DataInputStream din = new DataInputStream (System.in);
s=din.readLine();
tmp = Double.parseDouble(s);
System.out.println("Ergebnis " + tmp); // new line
}
}
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Keyboard Input - Scanner
java.util.Scanner mit JDK 5.0import java.util.*;
class EchoScanner
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Input: ");
String input = sc.next();
System.out.println("Result: " + input);
}
}
DocScanner:
A simple text scanner which can parse primitive types and strings using regular
expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches
whitespace. The resulting tokens may then be converted into values of different types
using the various next methods.
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Random Access, etc.
Instances of this class support both reading and writing to a
random access file.
A random access file behaves like a large array of bytes stored in
the file system. There is a kind of cursor, or index into the implied
array, called the file pointer; input operations read bytes starting at
the file pointer and advance the file pointer past the bytes read. If
the random access file is created in read/write mode, then output
operations are also available; output operations write bytes
starting at the file pointer and advance the file pointer past the
bytes written. Output operations that write past the current end of
the implied array cause the array to be extended. The file pointer
can be read by the getFilePointer method and set by the seek
method.
Fachbereich Informatik und Elektrotechnik
Programming in Java Helmut Dispert
Random Access, etc.
� Random Access – RandomAccessFile
- long getFilePointer() – returns the current offset in
this file
- void seek(long pos) – sets the file-pointer offset
- several read methods – readLine, readInt, readUTF
- several write methods
� Objects
- ObjectInputStream
- ObjectOutputStream
� others
Ref.:
Package java.ioJava.io