您的位置:首页 > 编程语言 > PHP开发

内存流操作ByteArrayInputStream,ByteArrayOutputStream

2018-01-21 22:22 453 查看


内容:

 ·当我们需要使用IO操作但是不需要生成文件,就使用内存流实现输入输出操作。

·在java.io包中提供两组操作:

  ·字节内存流:ByteArrayInputStream
, ByteArrayOutputStream

  ·字符内存流:CharArrayReader
, CharArrayWriter

 构造方法:public
ByteArrayInputStream (byte[]buf):将操作数据设置到输入流。

  public
ByteArrayOutputStream()从内存输出数据。

·示例代码1:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DDRDemo01 {
public static void main(String[] args) throws IOException {
String str="Hello*World!!!";//需要被转换的字符串
//将数据保存到内存,然后取出每一个数据
//将要读取的内存设置到内存输入流中,利用想上转型
InputStream input=new ByteArrayInputStream(str.getBytes());
//使用ByteArrayOutputStream()将所有内存流数据取出
OutputStream output=new ByteArrayOutputStream();
int temp=0;
//通过循环,将数据保存到内存输出流中
while ((temp=input.read())!=-1) {//每次读取一个数据
output.write(Character.toUpperCase(temp));
}
System.out.println(output);//调用toString方法
input.close();
output.close();

}
} ·示例代码2:
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class DDRDemo02 {
public static void main(String[] args) throws IOException {
File file01 = new File("D:" + File.separator + "贪玩蓝月.txt");
File file02 = new File("D:" + File.separator + "传奇霸业.txt");
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in01 = new FileInputStream(file01);
InputStream in02 = new FileInputStream(file02);
int temp = 0;
// 把所有的数据存在内存输出流当中
while ((temp = in01.read()) != -1) {
out.write(temp);
}
while ((temp = in02.read()) != -1) {
out.write(temp);
}
byte[] data = out.toByteArray();
out.close();
in01.close();
in02.close();
System.out.println(new String(data));

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: