IO-05内存操作流06管道流

JAVA中可以将输出的位置设置在内存上,此时使用ByteArrayInputStream,ByteArrayOutputStream来完成输入,输出功能。

利用这两个类实现大小字母的转换:

package lianxijihe;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class lianxi049 {
	public static void main(String[] args){
		String str = "AAAAAAAAA";
		InputStream in = new ByteArrayInputStream(str.getBytes());
		OutputStream out = new ByteArrayOutputStream();
		int temp;
		try {
			while((temp=in.read())!=-1){
				char c = (char)temp;
				out.write(Character.toLowerCase(c));
				
			}
			String newStr = out.toString();
			in.close();
			out.close();
			System.out.println(newStr);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
线程通讯流(管道流)的使用

管道流的主要作用是可以进行两个线程间的通讯,分为管道输出流PipedOutputStream,管道输入流PipedInputStream,如果想要进行管道流输出,则必须把输入流连在输入流上,如下图:

下面使用管道流进行输入输出操作:

package lianxijihe;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class lianxi050 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Send s = new Send();
		Receive r = new Receive();
		try {
			s.getPos().connect(r.getPis());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		new Thread(s).start();
		new Thread(r).start();
		
	}

}
class Send implements Runnable{
	private PipedOutputStream pos = null;
	public Send(){
		this.pos = new PipedOutputStream();
		
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		String str ="HelloWorld!!";
		 try {
			this.pos.write(str.getBytes());
			pos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	public PipedOutputStream getPos(){
		return this.pos;
	}
}
class Receive implements Runnable{
	private PipedInputStream pis = null;
	
	public Receive(){
		this.pis = new PipedInputStream();
	}

	@Override
	public void run() {
		byte[] b =new byte[1024];
		int len = 0;
		try {
			len = pis.read(b);
			pis.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println(new String(b,0,len));
	}
	
	public PipedInputStream getPis(){
		return this.pis;
	}
	
	
	
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值