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;
}
}