说起io流最常用的地方就是文件操作,例如从一个文件中读取内容,或者把内容输入到文件中,这些都是io流的基本操作。其实流在编程语言中是一个抽象概念,流的概念:流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。它的特性是进行数据传输。所以io流不仅仅用于文件内容的传输。
接下来演示一下自定义输入输出流并利用流的概念复制一个字符串,将字符串s中的内容流向s2。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Test {
public static void main(String[] args) throws IOException {
String s="123456";
StringBuilder s2=new StringBuilder();
BufferedInputStream bis=new BufferedInputStream(new MyInputStream(s));
BufferedOutputStream bos=new BufferedOutputStream(new MyOutputStream(s2));
byte[] bytes=new byte[1024];
int length;
while((length=bis.read(bytes))!=-1) {
bos.write(bytes,0,length);
}
bos.flush();
bos.close();
bis.close();
System.out.println(s2);
}
}
class MyOutputStream extends OutputStream{
private StringBuilder bs;
public MyOutputStream(final StringBuilder b) {
this.bs=b;
}
@Override
public void write(int b) throws IOException {
// TODO Auto-generated method stub
bs.append((char)b);
}
}
class MyInputStream extends InputStream{
private String s=null;
private int location=0;
private int length;
public MyInputStream(final String s) {
this.s=s;
length=s.length();
}
@Override
public int read() throws IOException {
// TODO Auto-generated method stub
if(location>=length) {
return -1;
}
return s.charAt(location++);
}
}
这样s2中的内容就是123456