Java的io流,是一个很容易混淆的概念,里面涉及了很深层次的类继承,并且应用了著名的装饰模式,首先,我们来看下io流的具体类提及其应用和概念;
首先,流是什么?流是什么?流来自java.io包,
形象的比喻——水流 ,文件======程序 ,文件和程序之间连接一个管道,水流就在之间形成了,自然也就出现了方向:可以流进,也可以流出.便于理解,这么定义流: 流就是一个管道里面有流水,这个管道连接了文件和程序。
根据流的方向划分,我们分为流进流和流出流:
流进流:
public abstract class InputStream
extends Object
implements Closeable
此抽象类是表示字节输入流的所有类的超类。
需要定义 InputStream
子类的应用程序必须总是提供返回下一个输入字节的方法。
这个类是所有流入流的超类,他提供了从程序从数据源读取数据的方式:
read()
从输入流中读取数据的下一个字节。
int read(byte[] b)
从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。
int read(byte[] b, int off, int len)
将输入流中最多 len 个数据字节读入 byte 数组。
其中辅助这个读取方法的另外两个方法是:
int available()
返回此输入流下一个方法调用可以不受阻塞地从此输入流读取(或跳过)的估计字节数。
long skip(long n)
跳过和丢弃此输入流中数据的 n 个字节。
相对而言:流出流正好相反:
public abstract class OutputStreamextends Objectimplements Closeable, Flushable此抽象类是表示输出字节流的所有类的超类。输出流接受输出字节并将这些字节发送到某个接收器。
需要定义 OutputStream 子类的应用程序必须始终提供至少一种可写入一个输出字节的方法。
void write(byte[] b)
将 b.length 个字节从指定的 byte 数组写入此输出流。
void write(byte[] b, int off, int len)
将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
abstract void write(int b)
将指定的字节写入此输出流
正好,这个两个接口提供了java 的基本输入输出功能;
字节流在传输的时候,更多的是方便我们传输二进制的文件,如下:
package org.corey.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class IODemo {
/**
* @param args
*/
public static void main(String[] args) {
File srcFile = new File("c:/a.jpg");
File tgtFile = new File("d:/a.jpg");
try {
FileInputStream fin = new FileInputStream(srcFile);
byte[] bts = new byte[fin.available()];
fin.read(bts, 0, fin.available() - 1);
fin.close();
FileOutputStream fos = new FileOutputStream(tgtFile);
fos.write(bts);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在此接口的功能基础上,根据数据来源的不同以及和数据流向的不同,扩展了几个类:分别是:
InputStream:
AudioInputStream, ByteArrayInputStream, FileInputStream, FilterInputStream, InputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream
OutputStream:
ByteArrayOutputStream, FileOutputStream, FilterOutputStream, ObjectOutputStream, OutputStream, PipedOutputStream
诸如:
package org.corey.servlet;
import java.io.ByteArrayInputStream;
import java.io.File;
public class IODemo {
/**
* @param args
*/
public static void main(String[] args) {
try {
byte[] buffer=new byte[]{1,2,3,4,5,6};
ByteArrayInputStream bts=new ByteArrayInputStream(buffer);
int byteValue;
while((byteValue=bts.read())!=-1){
System.out.println(byteValue);
}
} catch (Exception e) {
System.out.println("create the fin is error");
e.printStackTrace();
}
}
}
package org.corey.servlet;
import java.io.ByteArrayOutputStream;
public class IODemo {
/**
* @param args
*/
public static void main(String[] args) {
try {
byte[] buffer = new byte[] { 1, 2, 3, 4, 5, 6 };
byte[] targetBuffer;
ByteArrayOutputStream bos = new ByteArrayOutputStream(10);
bos.write(buffer);
targetBuffer=bos.toByteArray();
int arrayIndex=0;
while(arrayIndex<buffer.length){
System.out.println(targetBuffer[arrayIndex]);
arrayIndex++;
}
} catch (Exception e) {
System.out.println("create the fin is error");
e.printStackTrace();