两大字节抽象流:
1.inputstream
2.outputstream
字节流与字符流的区别:
1.字节流可以处理所有类型的文件
2.字节流没有缓冲区,而字符流有缓冲区
3.字符流只能处理文本格式的文件
操作文件的字节流:
1.FileInputStream
2.FileOutputStream
转换流:
1.InputStreamReader
2.OutputStreamWriter
此流是字节流通向字符流的桥梁
缓冲流:
BufferedInputStream
BufferedOutputStream
此流相当于在字节流外层套上一层管道;可以提高速度
内存操作流:
ByteArrayInputStream
ByteArrayOutputStream
此流用来操作内存中的数据
案例:
@Test
public void byteInputStream(){
String info = "test ok";
ByteArrayInputStream bis = null;
ByteArrayOutputStream bos = null;
try{
bis = new ByteArrayInputStream(info.getBytes());//相当于把内存中info所指向的内容相连
bos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
while((bis.read(buff)) != -1){//从内存中读数据
bos.write(buff);//把数组byte数组中的内容写入到此输出流中
}
System.out.println(bos.toString());//把此输出流中的内容转换为字符串
}catch(Exception e){
}finally{
try {
bis.close();
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
管道流:
1.PipedInputStream
2.PipedOutputStream
此流用于线程之间的通信
案例:从一个线程上获取到另一个线程上的值
public class PipedOutputStreamDemo {
public static void main(String[] args) {
Father father = new Father();
Son son = new Son();
father.test();
son.test();
try {
father.getPo().connect(son.getPs());//把输出管道流与输入管道流链接一起
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread t1 = new Thread(father);
Thread t2 = new Thread(son);
t1.start();
t2.start();
}
}
class Father implements Runnable{
PipedOutputStream po = null;
public PipedOutputStream getPo() {
return po;
}
public void test(){
po = new PipedOutputStream();
}
@Override
public void run() {
String info = "最近过的好吗?";
while(true){
try {
po.write(info.getBytes());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Son implements Runnable{
PipedInputStream ps = null;
public PipedInputStream getPs() {
return ps;
}
public void setPs(PipedInputStream ps) {
this.ps = ps;
}
Father father = null;
byte [] buff = new byte[1024];
public void test(){
father = new Father();
ps = new PipedInputStream();
}
public void run(){
int len = 0;
while(true){
try {
while((len = ps.read(buff)) != -1){
System.out.println(new String(buff,0,len));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
数据流:
1.DataInputStream
2.DataOutputStream
该留可以保存基本数据类型;例如:使用此流把程序中的数据写入到文件里面,如果数据中含有基本数据类型;它写入到文件中还是那个类型,只不过是乱码而已,当用此输入流读取出来时,还是原来的数据