java基础知识回顾之javaIO类--管道流PipedOutputStream和PipedIutputStream
管道流(线程通信流):管道流的主要作用是可以进行两个线程间的通讯,分为管道输出流(PipedOutputStream)、管道输入流(PipedInputStream),如果想要进行管道输出,则必须要把输出流连在输入流之上。如图所示:

1.管道输入流应该连接到管道输出流 ,输入流和输出流可以直接连接
2.使用多线程操作,结合线程进行操作。通常由某个线程从管道输入流中(PipedInputStream)对象读取。
并由其他线程将其写入到相应的端到输出流中。不能使用单线程对输入流对象向和输出流对象进行操作,因为会造成 死锁问题。
3.管道流连接:(1)使用构造方法进行连接PipedOutputStream(PipedInputStream snk) 创建连接到指定管道输入流的管道输出流。
(2)public void connect(PipedInputStream snk)throws IOException,使用connect方法进行连接
下面看代码:
package com.lp.ecjtu.io.piped;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedDemo {
public static void main(String[] args) {
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in = new PipedInputStream();
try {
out.connect(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//输出管道流连接输入管道流
new Thread(new OutputThread(out)).start();
new Thread(new InputThread(in)).start();
}
}
class InputThread implements Runnable{
private PipedInputStream in;
public InputThread(PipedInputStream in){
this.in = in;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
byte[] buff = new byte[1024];
int len = in.read(buff);
String s = new String(buff,0,len);
System.out.println(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class OutputThread implements Runnable{
private PipedOutputStream out;
public OutputThread(PipedOutputStream out){
this.out = out;
}
@Override
public void run() {
String str = "hello Piped!";
try {
out.write(str.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(out != null){
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
java基础知识回顾之javaIO类--内存操作流ByteArrayInputStream和ByteArrayOutputSteam(操作字节数组)
直接看代码:
package cn.itcast.io.p6.bytestream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ByteArrayStreamDemo {
/**
* @param args
* @throws IOException
* 特点
* 1.内存操作流
* 2.不操作底层资源,不调用操作系统的底层资源,操作内存中的数据,内存流不需要关闭
* 3.关闭流后还可以使用
* 本例:内存操作流完成的一个大小写字母转换的程序:
*/
public static void main(String[] args) {
String str = "HELLO WORLD!";
ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());//将内容输入到内存中
ByteArrayOutputStream bos = new ByteArrayOutputStream();//将内存中的数据输出
int ch = 0;
bis.skip(2);//跳过两个字节
System.out.println(bis.available());//返回此输入流读取的(或跳过)剩余的字节数
while((ch=bis.read())!=-1){
bos.write(Character.toLowerCase(ch));//将大小字符转化成小写
}
System.out.println(bos.toString());
}
}
输出:由于跳过两个字节,HELLO WORLD!总共12个字节,则剩余10个字节。
10
llo world!
