byte[] ----> File
- 建立字节读入流
建立字节数组输出流- 建立结果记录byte数组、中间byte数组、长度统计变量len
- 刷新流、将流转换到数组中
public static byte[] getBytesFromFile(String src) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(src));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] dest = null;
byte[] flush = new byte[1024];
int len = 0;
while (-1 != (len = is.read(flush))) {
bos.write(flush, 0, len);
}
bos.flush();
dest = bos.toByteArray();
return dest;
}
File ----> byte[]
1.建立字节数组输入流
建立字节输出流
2. 建立结果记录byte数组、中间byte数组、长度统计变量len
3. 刷新流、将流转换到数组中
public static void FileFromByteArray(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));
int len = 0;
byte[] flush = new byte[1024];
while (-1 != (len = is.read(flush))) {
os.write(flush, 0, len);
}
os.flush();
os.close();
is.close();
}
完整代码如下
package cn.hxh.io.other;
import java.io.*;
public class ByteArrayDemo02 {
public static void main(String[] args) throws IOException {
FileFromByteArray(getBytesFromFile("D:/aa/a.txt") , "d:/aa/c.txt");
}
public static void FileFromByteArray(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));
int len = 0;
byte[] flush = new byte[1024];
while (-1 != (len = is.read(flush))) {
os.write(flush, 0, len);
}
os.flush();
os.close();
is.close();
}
public static byte[] getBytesFromFile(String src) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(src));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] dest = null;
byte[] flush = new byte[1024];
int len = 0;
while (-1 != (len = is.read(flush))) {
bos.write(flush, 0, len);
}
bos.flush();
dest = bos.toByteArray();
return dest;
}
}
shimeath_rafael
发布了11 篇原创文章 · 获赞 0 · 访问量 66
私信
关注