IO学习(十一)利用字节数组流实现文件拷贝,QuesRemain

来源:互联网 发布:windows测试页打印失败 编辑:程序博客网 时间:2024/05/09 13:04

1.字节数组流

输出流:ByteArrayOutputStream bos=new ByteArrayOutputStream();

由于输出流有新增方法,所以这里不可以使用多态


输入流:ByteArrayInputStream bis=new ByteArrayInputStream(destByte);
  InputStream bis=new BufferedInputStream(new ByteArrayInputStream(destByte));


2.文件拷贝

之前使用节点流中的字节流进行文件的拷贝,利用字符流进行纯文本文件的拷贝,也可以使用处理流中的字节缓冲流与字符缓冲流进行文件/文本文件的拷贝,为了将字节数组流与之前的节点流联系在一起,这里利用字节数组流做中转站,实现文件的拷贝。


步骤一:利用文件输入流读取到被拷贝文件的数据,利用字节数组输出流保存在字节数组中

步骤二:利用字节数组输入流以及文件输出流,将数据写出到目的文件中。


代码:

public class ByteArrayDemo02 {public static void main(String[] args) throws IOException {byte[] data =getBytesFromFile("F:/Picture/test/test.txt");toFileFromByteArray(data,"F:/Picture/test/test2.txt");}/** * 2、字节数组  --程序->文件 */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();}/** * 1、文件  --程序->字节数组 * @return * @throws IOException  */public static byte[] getBytesFromFile(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;}}





3.问题

上面的代码将步骤1,2分为两个方法,如果不分开,如下面代码,拷贝不成功,原因不明

public class Demo08 {public static void main(String[] args) throws IOException {//文件源,以及文件目的地File src=new File("F:/Picture/test/test.txt");File dest=new File("F:/Picture/test/test2.txt");//字节数组,中转站byte[] destByte=new byte[1024];//选择文件流InputStream is=new BufferedInputStream(new FileInputStream(src));OutputStream os=new BufferedOutputStream(new FileOutputStream(dest));//选择字节数组流ByteArrayOutputStream bos=new ByteArrayOutputStream();InputStream bis=new BufferedInputStream(new ByteArrayInputStream(destByte));/** * 开始从文件中读取数据到字节数组中 */byte[] flush=new byte[1024];int len=0;while(-1!=(len=is.read(flush))){bos.write(flush, 0, len);}bos.flush();//获取数据destByte=bos.toByteArray();/** * 从字节数组中读取到目的文件中 */byte[] flush2 =new byte[1024];int len2 =0;while(-1!=(len2 =bis.read(flush2))){//写出到文件中os.write(flush2, 0, len2);}os.flush();bis.close();os.close();bos.close();is.close();}}






0 0