9. Stream
9. Stream
Hierarchy of InputStream
Hierarchy of OutputStream
InputStream
int read()
int read(byte buf[])
int read(byte buf[], int offset, int length)
void close()
OutputStream
int write(int c)
int write(byte buf[])
int write(byte buf[], int offset, int length)
void close()
void flush()
Example 1
Write a program using byte streams to copy a text file to another
file
Copy one byte at a time
Apply FileInputStream & FileOutputStream for the file I/O byte
streams
Hierarchy of Reader
Hiearchy of Writer
Reader
int read()
int read(char buf[])
int read(char buf[], int offset, int length)
void close()
Writer
int write(int c)
int write(char buf[])
int write(char buf[], int offset, int length)
void close()
void flush()
s.useDelimiter(“,\\s*”); //Scanner s
String s;
try {
s = in.readLine();
}
catch (IOException e) {
...
}
try{
File file = new File(“C:/Users/vthnhan/Desktop/test”);
if(file.createNewFile()){….} //new file is created
else … //file already exists
}catch(IOException e){ e.printStackTrace() }
Define an abstract file name for the test file in the directory
C:/Users/vthnhan/Desktop/
Creates a new File instance by converting the given pathname string into an
abstract pathname.
Creates a new File instance from a parent abstract pathname and a child
pathname string
Creates a new File instance from a parent pathname string and a child
pathname string
File(URI uri)
Creates a new File instance by converting the given file: URI into an abstract
pathname.
s = in.readLine();
while (s != null) {
out.println(s);
s = in.readLine();
}
in.close();
out.close();
}
catch (IOException e) { e.printStackTrace(); }
}
}
Write data
FileOutputStream: write data to a file
DataOutputStream: write primitive data
ObjectOutputStream: write objects
try {
FileOutputStream fout = new FileOutputStream(args[0]);
DataOutputStream dout = new DataOutputStream(fout);
try {
FileInputStream fin = new FileInputStream(args[0]);
DataInputStream din = new DataInputStream(fin);
while (true) {
System.out.println(din.readInt());
}
}
catch (EOFException e) {}
catch (IOException e) {e.printStackTrace();
}
}
}
Example
import java.io.Serializable;
try {
FileOutputStream fout = new FileOutputStream(“test.txt”);
ObjectOutputStream out = new ObjectOutputStream(fout);
out.close();
}
catch (IOException e) {e.printStackTrace(); }
}
}
try {
FileInputStream fin = new FileInputStream( “test.txt”);
ObjectInputStream in = new ObjectInputStream(fin);
while (true) {
r = (Record) in.readObject();
System.out.println(r);
}
}
catch (EOFException e) { System.out.println("No more records"); }
catch (ClassNotFoundException e) {
System.out.println("Unable to create object");
}
catch (IOException e) { e.printStackTrace(); }
}
}
try {
File fout = new File(args[0]);
RandomAccessFile out = new RandomAccessFile(fout, "rw");
try {
File fin = new File(args[0]);
RandomAccessFile in = new RandomAccessFile(fin, "r");