我们的流操作除了在文件上操作,还可以在内存中操作
用到的类
ByteArrayInputStream 主要完成把文件写入内存
ByteArrayOutputStream 主要将内存中内容输出
利用内存流来完成一个字符串大小写的转换
public
class
ByteArrayDemo {
public
static
void
main(String[] args)
throws
Exception{
String str=
"HELLO WORLD"
;
ByteArrayInputStream in=
null
;
//内存输入流
ByteArrayOutputStream out=
null
;
//内存输出流
in=
new
ByteArrayInputStream(str.getBytes());
//向内存中输入内容
out=
new
ByteArrayOutputStream();
//准备输出
int
temp=0;
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);
}
}
结果:
hello world
内存流的作用一般是用来写临时文件的。
管道流的作用是用来进行两个线程之间的通信
管道流分为输出流和输入流
如果要进行线程之间的通信,即必须要把输入流接到输出流上
下面来验证一下管道流
class
Send
implements
Runnable{
private
PipedOutputStream
pip
=
null
;
//管道输出流
public
Send() {
this
.
pip
=
new
PipedOutputStream();
}
public
void
run() {
String str=
"hello world"
;
try
{
this
.
pip
.write(str.getBytes());
//输出信息
}
catch
(IOException e) {
//
TODO
Auto-generated catch block
e.printStackTrace();
}
try
{
this
.
pip
.close();
}
catch
(IOException e) {
//
TODO
Auto-generated catch block
e.printStackTrace();
}
}
public
PipedOutputStream getpip(){
return
pip
;
}
}
class
Receive
implements
Runnable{
PipedInputStream
p
=
null
;
public
Receive() {
this
.
p
=
new
PipedInputStream();
}
public
void
run() {
byte
b[]=
new
byte
[1024];
int
len=0;
try
{
len=
this
.
p
.read(b);
}
catch
(IOException e) {
//
TODO
Auto-generated catch block
e.printStackTrace();
}
try
{
p
.close();
}
catch
(IOException e) {
//
TODO
Auto-generated catch block
e.printStackTrace();
}
System.
out
.println(
"接收的内容是:"
+
new
String(b,0,len));
}
public
PipedInputStream getP(){
return
p
;
}
}
public
class
PipDemo {
public
static
void
main(String[] args) {
Send s=
new
Send();
Receive r=
new
Receive();
try
{
s.getpip().connect(r.getP());
//接通管道
}
catch
(IOException e) {
//
TODO
Auto-generated catch block
e.printStackTrace();
}
new
Thread(s).start();
new
Thread(r).start();
}
}
结果:
接收的内容是:hello world