Beruflich Dokumente
Kultur Dokumente
Hard
011
110
011
000
111
001
110
011
110
001
100
010
101
111
Disk Main Memory
0
Java
Program
IO Stream
Text File
Stream A Stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by
the Java System. All Streams behave in the same manner, even if the actual physical devices to which they are linked differ.
Thus, the same I/O classes and methods can be applied to any type of device. This means that an input stream can abstract
many different kind of input: from a disk file, a keyboard, or a network connection. Streams are a clean way to deal with
input/output without having every part of your code understands the difference between a keyboard and a network.
Byte Stream & Character Stream : Java define two types of streams :byte and character. Byte streams provide a
convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary
data. Character streams provide a convenient means for handling input & output of characters. They used Unicode and,
therefore, can be internationalized. Also, in some cases, character streams are more efficient than byte stream.
IO Stream
Character Stream
Byte Stream
Reader Writer
InputStream OutputStream
BufferedReader BufferedWriter
AudioInputStream, ByteArrayOutputStream
LineNumberReader CharArrayWriter
ByteArrayInputStream FileOutputStream
FilterReder FilterWriter
FileInputStream FilterOutputStream
InputStreamReader InputStreamWriter
FilterInputStream BufferedOutputStream
FileReader FileWriter
ObjectOutputStream
BufferedInputStream
StringReader PrintWriter
PipedOutputStream
ObjectInputStream
CharArrayReader StringWriter
DataOutputStream
StringBufferInputStrea
PrintStream
DataInputStream
Example 2.A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the
stream. An internal counter keeps track of the next byte to be supplied by the read method.
import java.io.*;
class DemoByteArrayInputStream{
public static void main(String args[]){
byte b[]={65, 67,69,71,73,75,77,79};
ByteArrayInputStream bis=new ByteArrayInputStream(b);
int x;
while((x=bis.read())!=-1){
System.out.println(x+" :"+(char)x);
}
}
}
import java.io.*;
class ShowFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: File not found ");
return;
}
fin.close();
}
}
2
Example 4.
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host
environment. FileInputStream is meant for reading streams of raw bytes such as image data.
import java.io.*;
class DemoFileInputStream {
public static void main(String args[])throws IOException{
byte b[]={65, 67,69,71,73,75,77,79};
FileInputStream fis=new FileInputStream("Input.txt");
int x;
while((x=fis.read())!=-1){
System.out.print((char)x);
if(x==0)
System.out.println();
}
System.out.println();
}
}
Example 5.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.
import java.io.*;
class TestDataInputStream {
public static void main(String args[])throws IOException{
FileInputStream fis=new FileInputStream("Input.txt");
DataInputStream dis=new DataInputStream(fis);
byte b;
while((b=dis.readByte())!=-1){
System.out.print((char)b);
if(b==0)
System.out.println();
}
System.out.println();
}
}
FileOutpuStream
A FileOutputStream is an output stream for writing data to a File. Whether or not a file is available or may be created
depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one
FileOutputStream (or other file-writing object) at a time.
Example 6.FileOutputStream
import java.io.*;
class DemofileOutputStreamStream {
public static void main(String args[])throws IOException{
FileOutputStream fos=new FileOutputStream("Output.txt",true);
//Creates an output file stream to write to the file with the specified name.
byte b[]={78,105,114,111,116,104,32,76,97,107,109,97,108,32,83,97,
109,97,114,97,119,105,99,107,114,97,109,97,13,10,78,111,
46,53,48,54,32,49,47,51,44,13,10,71,97,108,108,
101,32,82,100,44,13,10,80,97,110,97,100,117,114,97,46};
fos.write(b);
import java.io.*;
class CopyFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try {
// open input file
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Input File Not Found");
return;
}
// Copy File
try {
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
} catch(IOException e) {
System.out.println("File Error");
}
fin.close();
fout.close();
}
}
PrintStream
A PrintStream adds functionality to another output stream, namely the ability to print representations of various data
values conveniently. Two other features are provided as well.
PrintStream(File file)
Creates a new print stream, without automatic line flushing, with the specified file.
PrintStream(OutputStream out)
Create a new print stream.
4
PrintStream(String fileName)
IO Stream
InputStreamReader(System.in)
Java
10
10
10
11
01
ha
er
ra
ct
C
1
1
1
10
0
0
01
1
1
10
10
0
0
01
1
1
1
0
0
0
0
1
s
Keyboard Program
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters
using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's
default charset may be accepted.
FileInputStream(“Input.txt”)
Hard
Disk
=x
10
10
10
11
01
01
01
67
76
65
66
56
ha
er
ra
ct
C
0
1
1
1
1
0
0
0
0
1
1
1
1
0
0
0
1
1
1
1
0
0
0
1
1
1
0
0
0
0
1
s
Java
InputStreamReader(FileInputStream)
Input.txt
Program
Example 11.(InputStreamReader)
import java.io.*;
class DemoInputStreamReader2{
public static void main(String args[])throws IOException{
5
InputStreamReader isr=new InputStreamReader(System.in);
//Create an InputStreamReader that uses the input from the keyboard
System.out.print("Input Character :");
int x=isr.read(); //This method read a character from the keyboard
System.out.println(x+" "+(char)x);
}
}
Example 12. InputStreamReader with FileInputStream Read character from file (Input.txt)
import java.io.*;
class DemoInputStreamReader3{
public static void main(String args[])throws IOException{
InputStreamReader isr1=new InputStreamReader(new FileInputStream("Input.txt"));
while((x=isr1.read())!=-1){
System.out.print((char)x);
}
isr.close();
}
}
Example 13.BufferedReader
import java.io.*;
class DemoBufferedReader {
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(new
FileInputStream("Input.txt")));
String s;
while((s=br.readLine())!=null){
System.out.println(s);
}
}}
Example 14.BufferedReader
import java.io.*;
class DemoBufferedReader2 {
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int x,y,z;
System.out.print("Input a Number :");
x=Integer.parseInt(br.readLine());
System.out.print("Input a Number :");
y=Integer.parseInt(br.readLine());
z=x+y;
System.out.println("X + Y :"+z);
}
}
FileReader
IO Stream
Hard
Java
56
65
76
56
65
10
10
10
11
01
Disk
1
1
0
0
0
1
1
1
0
0
0
0
1
Program
FileReader(“Input.txt”)
Input.txt
Example 15.
import java.io.*;
class DemoFileReader {
public static void main(String args[])throws IOException{
FileReader fr=new FileReader("Input.txt");
int x;
while((x=fr.read())!=-1){
System.out.println((char)x);
6
}
}
}
IO Stream
Hard
Java
90
68
56
56
65
a
m
ra
ck
wi
a
ar
m
Sa
h
rot
Ni
10
10
10
11
01
0
0
0
1
1
1
0
0
0
0
1
Disk
Program
FileReader(“Input.txt”) DufferedReader(FileReader)
Input.txt
Example 16.
import java.io.*;
class DemoFileReader2 {
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new FileReader("Input.txt"));
String s;
while((s=br.readLine())!=null){
System.out.println(s);
}
}
}
Writing Characters
Example 17.BufferedWriter
BufferedWriter class can write strings to a Disk file using FileWriter stream
import java.io.*;
class DemoBufferedWriter1 {
public static void main(String args[])throws IOException{
BufferedWriter bw=new BufferedWriter(new FileWriter("Output.txt"));
String s="Institute of Java & Technological Studies";
bw.write(s);
bw.close();
}
}
Example 18.InputStreamWriter(Console)
This program demonstrates how write characters on console using OutputStreamWriter
import java.io.*;
class DemoOutputStreamWriter{
public static void main(String args[])throws IOException{
OutputStreamWriter bw=new OutputStreamWriter(System.out);
String s="Institute of Java & Technological Studies";
bw.println(s);
bw.close();
}
}
Example 19.InputStreamWriter(FileOutputWriter)
import java.io.*;
class DemoOutputStreamWriter2{
public static void main(String args[])throws IOException{
FileOutputStream fos= new FileOutputStream("Input.txt");
7
OutputStreamWriter osw=new OutputStreamWriter(fos);
String s1="Institute of Java & Technological Studies";
String s2="No 506 1/3, Galle Road,";
String s3="Panadura.";
osw.write(s1);
osw.write(s2);
osw.write(s3);
osw.close();
}
}
PrintWriter
PrintWriter(File file)
Creates a new PrintWriter, without automatic line flushing, with the specified file.
PrintWriter(OutputStream out)
Create a new PrintWriter, without automatic line flushing, from an existing OutputStream.
PrintWriter(OutputStream out, boolean autoFlush)
Create a new PrintWriter from an existing OutputStream.
PrintWriter(String fileName)
Creates a new PrintWriter, without automatic line flushing, with the specified file name.
PrintWriter(Writer out)
Create a new PrintWriter, without automatic line flushing.
PrintWriter(Writer out, boolean autoFlush)
Create a new PrintWriter.
Example 20.PrintWriter(System.out)
import java.io.*;
class DemoPrintWriter{
public static void main(String args[])throws IOException{
PrintWriter pw=new PrintWriter(System.out, true );
pw.println("Institute of Java & Technlogical Studies");
pw.println("No. 506 1/3, Galle Rd,");
pw.println("Panadura.");
pw.println();
pw.write(65);
pw.write(32);
pw.println();
pw.append('g');
pw.println();
pw.println(23.34);
pw.println(23);
pw.flush();
}
}
Example 21.PrintWriter(“DiskFile”)
import java.io.*;
class DemoPrintWriter2{
public static void main(String args[])throws IOException{
PrintWriter pw=new PrintWriter("Output.txt" );
pw.println("Institute of Java & Technlogical Studies");
pw.println("No. 506 1/3, Galle Rd,");
pw.println("Panadura.");
pw.println();
pw.write(65);
pw.write(32);
pw.println();
pw.append('g');
8
pw.println();
pw.println(23.34);
pw.println(23);
pw.flush();
}
}
StringWriter()
A character stream that collects its output in a string buffer, which can then be used to construct a string.
StringWriter()
Create a new string writer, using the default initial string-buffer size.
StringWriter(int initialSize)
Create a new string writer, using the specified initial string-buffer size.
Example 22.StringWriter()
import java.io.*;
class DemoStringWriter{
public static void main(String args[])throws IOException{
StringWriter sw=new StringWriter();
sw.write("IJTS");
System.out.println(sw);
sw.write("- Institute of Java & Technological Studies");
System.out.println(sw);
}
}
ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in
the Java Virtual Machine. Classes are loaded as required using the standard mechanisms.
ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in
the Java Virtual Machine. Classes are loaded as required using the standard mechanisms.
Example 23.ObjectOutputStream
Constructors
ObjectOutputStream(OutputStream out) Creates an ObjectOutputStream that writes to the specified
OutputStream.
import java.io.*;
class Cat implements Serializable {
int age;
String name;
9
// Serialize a cat object and save it on a disk file(CatObject.ser)
class DemoObjectOutputStream{
public static void main(String args[]) throws Exception{
FileOutputStream fis=new FileOutputStream("CatObjects.ser");
ObjectOutputStream oos=new ObjectOutputStream(oos);
// Serialize a cat object and save it on the console (but cannot read it)
class DemoObjectOutputStream{
public static void main(String args[]) throws Exception{
ObjectOutputStream oos=new ObjectOutputStream(System.out);
File(String directorypath);
File(String derectorypath, String filename);
File(File dirObj, String filename);
File(URI uriObj);
E.g.
File f1=new File(“/”);
File f2=new File(“/”,”autoexec.bat”);
File f3=new File(f1,”autoexec.bat”);
The first Fi le object is constructed with a directory path as the only argument. The second includes two
arguments-the path and the file name. The third includes the file path assign to f1 and a file name; f3 refers to the
same file as f3.
File defines many methods that obtain the standard properties of a file object. For example, get Na me () returns
the name of the file, get Pa re nt () returns the name of the parent directory, and exist s( ) returns true if the file is
exists, false if it does not.
Example 24.
import java.io.*;
class FileDemo1 {
static void p(String s) {
System.out.println(s);
}
Example 25.
import java.io.*;
class CreateAFile {
public static void main(String [] args) {
try { // warning: exceptions possible
boolean newFile = false;
File file = new File("fileWrite1.txt"); // it's only an object
System.out.println(file.exists()); // look for a real file
newFile = file.createNewFile(); // maybe create a file!
System.out.println(newFile); // already there?
System.out.println(file.exists()); // look again
} catch(IOException e) { }
}
}
If you compile and run this program, when you look at the contents of your current directory,
you'll discover absolutely no indication of a file called fileWrite1.txt. When you make a new
instance of the class File, you're not yet making an actual file, you're just creating a filename.
Example 26.
import java.io.*;
class DemoFileDirectory {
static void p(String s) {
System.out.println(s);
}
String fileList[]=f1.list();
for(String fileName:fileList) p(fileName);
}
}
}
class DemoFileDirectory {
static void p(String s) {
System.out.println(s);
}
11
for(String fileName:fileList) p(fileName);
}
}
Directories
A directory is a File that contains list of other files and directories. When you create a File object and it is a
directory, the isDirectory() method will return true. In this case, you can call lis() on that object to extract the
list of other files and directories inside. It has two forms.
String[] list();
// Using directories.
import java.io.File;
Exam Objectives
I/O is a huge topic in general, and the Java APIs that deal with I/O in one fashion or another are
correspondingly huge. A general discussion of I/O could include topics such as file I/O, console
I/O, thread I/O, high-performance I/O, byte-oriented I/O, character-oriented I/O, I/O filtering and
wrapping, serialization, and more. Luckily for us, the I/O topics included in the Java 5
exam are fairly well restricted to file I/O for characters, and serialization.
Here's a summary of the I/O classes you'll need to understand for the exam:
File The API says that the class File is "An abstract representation of file and directory
pathnames." The File class isn't used to actually read or write data; it's used to work at
a higher level, making new empty files, searching for files, deleting files, making
directories, and working with paths.
FileReader This class is used to read character files. Its read() methods are fairly low-
level, allowing you to read single characters, the whole stream of characters, or a fixed
number of characters. FileReaders are usually wrapped by higher-level objects such as
BufferedReaders, which improve performance and provide more convenient ways to
work with the data.
BufferedReader This class is used to make lower-level Reader classes like FileReader
more efficient and easier to use. Compared to FileReaders, BufferedReaders read
relatively large chunks of data from a file at once, and keep this data in a buffer. When
you ask for the next character or line of data, it is retrieved from the buffer, which
minimizes the number of times that time-intensive, file read operations are performed.
In addition, BufferedReader provides more convenient methods such as readLine(), that
allow you to get the next line of characters from a file.
FileWriter This class is used to write to character files. Its write() methods allow you to
write character(s) or Strings to a file. FileWriters are usually wrapped by higher-level
Writer objects such as BufferedWriters or PrintWriters, which provide better
performance and higher-level, more flexible methods to write data.
12
BufferedWriter This class is used to make lower-level classes like FileWriters more
efficient and easier to use. Compared to FileWriters, BufferedWriters write relatively
large chunks of data to a file at once, minimizing the number of times that slow, file
writing operations are performed. In addition, the BufferedWriter class provides a
newLine() method that makes it easy to create platform-specific line separators
automatically.
PrintWriter This class has been enhanced significantly in Java 5. Because of newly
created methods and constructors (like building a PrintWriter with a File or a String),
you might find that you can use PrintWriter in places where you previously needed a
Writer to be wrapped with a FileWriter and/or a BufferedWriter. New methods like
format(), printf(), and append() make PrintWriters very flexible and powerful.
13