1.字节数组流基础读写
public class ByteArrayDemo01 {
public static void main(String[] args) throws IOException {
read(write());
}
public static byte[] write() throws IOException {
byte[] dest = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String msg = "操作与文件输入流操作一致";
byte[] info = msg.getBytes();
bos.write(info, 0, info.length);
dest =bos.toByteArray();
bos.close();
return dest;
}
public static void read(byte[] src) throws IOException {
InputStream is = new BufferedInputStream(new ByteArrayInputStream(src));
byte[] flush = new byte[1024];
int len = 0;
while (-1 != (len = is.read(flush))) {
System.out.println(new String(flush, 0, len));
}
is.close();
}
}
2.字节数组流实现文件读取、写出
package test.others;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteArrayDemo02 {
public static void main(String[] args) throws IOException {
byte[] bs = getByteFromFile("E:\\test\\2.pdf");
toFileFromByteArray(bs, "E:\\test\\222.pdf");
}
public static void toFileFromByteArray(byte[] src, String destPath) throws IOException {
File dest = new File(destPath);
InputStream is = new BufferedInputStream(new ByteArrayInputStream(src));
OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
byte[] flush = new byte[1];
int len = 0;
while(-1 != (len = is.read(flush))) {
os.write(flush, 0, len);
}
os.flush();
os.close();
is.close();
}
public static byte[] getByteFromFile(String srcPath) throws IOException {
File src = new File(srcPath);
byte[] dest = null;
InputStream is = new BufferedInputStream(new FileInputStream(src));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] flush = new byte[1024];
int len = 0;
while (-1!=(len =is.read(flush))) {
bos.write(flush, 0, len);
}
bos.flush();
dest = bos.toByteArray();
bos.close();
is.close();
return dest;
}
}