package ioxuexi;
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.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 利用字節流和字節數組流是實現文件的復制
* @author User
*
*/
public class lianxi17 {
public static void main(String[] args) throws IOException {
byte[] data=get("E:/test/2.txt");
set(data, "e:/test/45.txt");
}
//將目的字節數組放到目標區域
public static void set(byte[] src,String destString) throws IOException{
//創建目的文件源
File destFile=new File(destString);
//利用字節數組輸入流錄入字節數組
InputStream isInputStream=new BufferedInputStream(new ByteArrayInputStream(src));
//利用字節輸出流輸出文件
OutputStream bosOutputStream=new BufferedOutputStream(new FileOutputStream(destFile));
//進行操作
byte[] flush=new byte[1024];
int len=0;
while (-1!=(len=isInputStream.read(flush))) {
bosOutputStream.write(flush,0,len);
}
//強制刷出
bosOutputStream.flush();
//關閉文件流,釋放資源
isInputStream.close();
bosOutputStream.close();
}
//通過字節流錄入和字節數輸出將源文件轉換為字節數組
public static byte[] get(String pathname) throws IOException {
//創建文件源
File srcFile=new File(pathname);
byte[] dest=null;
//利用字節輸入流將目的地址的文件進行錄入
InputStream isInputStream=new BufferedInputStream(new FileInputStream(srcFile));
//創建字節數組輸出流
ByteArrayOutputStream bosArrayOutputStream=new ByteArrayOutputStream();
//進行字節數組錄入
byte[] flush=new byte[1024];
int len=0;
while (-1!=(len=isInputStream.read(flush))) {
bosArrayOutputStream.write(flush,0,len);
}
bosArrayOutputStream.flush();
//關閉文件流,釋放資源
isInputStream.close();
bosArrayOutputStream.close();
//返回一個字節數組
return bosArrayOutputStream.toByteArray();
}
}