package com.gk;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 通过文件流和字节数组流实现文件的拷贝
* @author GuoKe
*
*/
public class IOTest9 {
public static void main(String[] args) {
byte[] bt = fileToByteArray("C:/Users/GK/Desktop/test.jpg");
System.out.println(bt.length);
byteArrayToFile(bt, "C:/Users/GK/Desktop/test00.jpg");
}
public static byte[] fileToByteArray(String filePath) {
//1.创建源
File src = new File(filePath);
InputStream is = null;
ByteArrayOutputStream bs = null;
bs = new ByteArrayOutputStream();
try {
//2.选择流
is = new FileInputStream(src);
//3.操作
byte[] flush = new byte[1024];//缓冲容器
int len = -1;//接收长度
while((len=is.read(flush)) != -1) {
bs.write(flush,0,len);
}
bs.flush();
return bs.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(is!=null) {
//4.释放资源
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static void byteArrayToFile(byte[] src, String filePath) {
File dest = new File(filePath);
OutputStream os = null;
InputStream is = null;
try {
//2.选择流
os = new FileOutputStream(dest);
is = new ByteArrayInputStream(src);
//3.操作
byte[] flush = new byte[1024];//缓冲容器
int len = -1;//接收长度
while((len=is.read(flush)) != -1) {
os.write(flush,0,len);
}
os.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (os != null) {//alt+shift+z
os.close();
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
通过文件流和字节数组流实现文件的拷贝
最新推荐文章于 2022-04-23 14:54:27 发布
本文详细介绍了如何利用Java的文件流和字节数组流进行文件复制操作,包括步骤解析和代码示例,旨在提供一种高效、可靠的文件拷贝解决方案。
摘要由CSDN通过智能技术生成