整理思路如下
- 为什么要这样进行copy (我更愿意称它为
传输
)
因为这样以二进制的形式传输文件,可以实现文件的远距离传输,即通过这样可以实现服务器与用户之间文件的传输。
我们在本地发送请求时,计算机将请求编码
为二进制文件,当传送到服务器后,服务器将二进制文件进行解码,从而实现文件的传输
那么如何将文件编码
为二进制文件哪
将文件转化为字节数组存储到byteArray中,即对应上图的第二个方向
public static byte[] fileToByte(String filePath) throws IOException {
/**
* 1.图片到程序 使用FileInputStream 流
* 2.程序到字节数组 使用ByteArrayOutStream 通过baos写入到byteArray中 即写到缓存中
*/
//创建源
File src=new File(filePath);
//选择流 将文件通过FIleInputStream 转化为字节数组 再传送给字节输出流
InputStream in=null;//使用多态
ByteArrayOutputStream baos=null;
//操作
try {
in=new FileInputStream(src);
baos=new ByteArrayOutputStream();
int len=-1;
byte[] flush=new byte[1024*10];//设置缓冲区
while((len=in.read(flush))!=-1) {
baos.write(flush,0,len);
}
baos.flush();
return baos.toByteArray();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}finally {
baos.close();
in.close();
}
return null;
}
下面将缓存中的baos通过程序转化为图片文件
public static void byteTofile(byte[] src,String filePath) {
//将字节数组通过程序
//程序转化为图片
//1.创建源
File file=new File(filePath);
//选择流
InputStream isInputStream=null;
OutputStream os=null;
try {
isInputStream= new ByteArrayInputStream(src);//将字节数组通过flush写到文件输出流os中,即目标文件
os=new FileOutputStream(filePath);
//分段读取
byte[] flush=new byte[5];
int len=-1;
while((len=isInputStream.read(flush))!=-1) {
os.write(flush,0,len);
}
os.flush();
} catch (Exception e) {
// TODO: handle exception
}finally {
try {
if(null!=os) {
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
效果如下
2. 上述主要是用来传输的,当然如果是在本地进行文件的复制的话,可以直接将文件输入流(FileInputStream)和文件输出流(FileOutputStream)合并
代码如下
public class CopyFile {
public static void main(String[] args) {
copy("test.txt", "test1.txt");//实现copy功能
}
public static void copy(String srcPath,String destPath) {
//创建两个源文件
File source=new File(srcPath);//原文件
File destination=new File(destPath);//拷贝的文件
//选择流
InputStream in=null;
OutputStream out=null;
//操作
try {
//从原文件读取文字
in=new FileInputStream(source);//输入流
out=new FileOutputStream(destination);//输出流
byte[] flush=new byte[1024*1024];//缓冲大小
int len=-1;//作为判断是否读到输入流的末尾的标志
while((len=in.read(flush))!=-1) {
out.write(flush,0,len);
}
out.flush();
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
if(out!=null) {
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(in!=null) {
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}