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

JavaSE 高级 第10节 字节数组输出流ByteArrayOutputStream

2016-07-24 17:34 176 查看
2016-07-24

1,ByteArrayOutputStream

FileOutputStream 把文件作为写入的目的地

ByteArrayOutputStream 把字节数组作为写入的目的地

package com.java1995;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

public class Test {

public static void main(String[] args) {
String str = "abcdefghijklmnopqrstuvwxyz";
byte[] b = str.getBytes();

ByteArrayInputStream bais = new ByteArrayInputStream(b);
BufferedInputStream bis = new BufferedInputStream(bais);
int temp = 0;
try {
temp = bis.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count = 0;
while (temp != -1) {
System.out.print((char) temp);
try {
temp = bis.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(count++);
}
System.out.println(count);

}
}




package com.java1995;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class TestByteArrayOutputStream {

public static void main(String[] args) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String temp = "hello world hello everyone!";
byte[] b = temp.getBytes();

try {
bos.write(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(bos.toString());

byte[] b1 = bos.toByteArray();
for (int i = 0; i < b1.length; i++) {
System.out.print((char) b1[i]);

}
}
}




【参考资料】

[1] Java轻松入门经典教程【完整版】
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: