Java IO 文件拷贝

粗糙版

package 学习资料.IO流;

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;

public class _5_1_文件拷贝 {
    public static void main(String[] args) {
        byte[] path = FiletoByte("dext.txt");
        BytetoFile("a.txt",path);
    }
    public static byte[] FiletoByte(String filepath) {
        File src = new File(filepath);                                           //建立文件对象

        InputStream is = null;                                                 //字节输入流
        ByteArrayOutputStream baos = null;                                        //字节操作流

        try {
            is = new FileInputStream(src);                                        //打开文件对象
            baos = new ByteArrayOutputStream();                                        //获得操作对象

            byte[] flush = new byte[1024*10];                                      //字节数组缓存
            int len = -1;                                                     //单次长度

            while((len = is.read(flush)) != -1)                                     //缓存获得文件信息
                baos.write(flush,0,len);                                          //将缓存信息写入操作对象

            baos.flush();                                                     //刷新操作对象
            return baos.toByteArray();                                           //将操作对象存储的字节信息返回

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }finally {
            try {
                if(is != null)  is.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public static void BytetoFile(String filePath,byte[] src) {
        File dest = new File(filePath);                                              //建立文件对象

        InputStream is = null;                                           //输入字节流
        OutputStream os = null;                                                    //输出字节流

        try {
            is = new ByteArrayInputStream(src);                                        //将src写入对象
            os = new FileOutputStream(dest);                                       //打开文件对象

            byte[] flush = new byte[5];                                              //字节输出缓存
            int len = -1;                                                     //单次长度

            while((len = is.read(flush)) != -1)                                        //从将输入流写入缓存
                os.write(flush,0,len);                                           //将缓存写进文件

            os.flush();                                                          //刷新输出流

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }finally {
            try {
                if( os != null) os.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

改进版

package 学习资料.IO流;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 封装拷贝
 * 封装关闭
 *
 */
public class _5_1_FileUtiles_文件拷贝 {
    public static void main(String[] args) {

        //文件-->>文件
        try {
            //所有文件的复制都可以这样使用,包括但不限于png,jpg,gif,txt,class等
            InputStream iStream = new FileInputStream("a.txt");
            OutputStream oStream = new FileOutputStream("a_copy.txt");

            BytetoFile(iStream,oStream);
            // close(iStream,oStream);

        } catch (IOException e) {
            e.printStackTrace();
        }

        //文件-->>字节数组
        byte[] information = null;
        try {

            InputStream iStream = new FileInputStream("a_copy.png");
            ByteArrayOutputStream oStream = new ByteArrayOutputStream();

            BytetoFile(iStream,oStream);
            information = oStream.toByteArray();
            // close(iStream,oStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //字节数组-->>文件
        try {
            //所有文件的复制都可以这样使用,包括但不限于png,jpg,gif,txt,class等
            InputStream iStream = new ByteArrayInputStream(information);
            OutputStream oStream = new FileOutputStream("copy.png");

            BytetoFile(iStream,oStream);
            // close(iStream,oStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
        /**
         * 之前想过明明可以直接将文件复制为什么还需要转换成字节数组这个中间变量呢?
         * 转换成字节数组的优点在于不只可以在本地进行传输(复制)文件了,因为网络只能接收字节流,所以可以将文件转化成字节数组传输到其他主机上
         * 其次,字节数组可以进行加密,可以保证数据在网络传输上的安全性
         * 还有就是可以将单个文件拆分成多个小文件,比如别人想爬取一个视频但是只能爬取到一个个小视频无法整合,整合手段对方爬取不到从而达到保护文件的目的
         */
    }

    public static void BytetoFile(InputStream is,OutputStream os) {
        try(InputStream is1 =
                    new BufferedInputStream(is);            //JDK1.8中的try-with-resources语法糖,这样写就可以省掉close部分
            OutputStream os1 =
                    new BufferedOutputStream(os)) {          //可以省去close 的封装操作1

            //Buffered可以提高效率操作方式没变(类似与装饰模式)
            byte[] flush = new byte[1024];                                        //字节输出缓存
            int len = -1;                                                     //单次长度

            while((len = is1.read(flush)) != -1)                                       //从将输入流写入缓存
                os1.write(flush,0,len);                                              //将缓存写进文件

            os1.flush();                                                         //刷新输出流

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
    }
    public static void close(InputStream is,OutputStream os) {
        try {
            if( os != null) os.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if(is !=null)is.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //接口是一个特殊的类,也可以作为参数
    //				↓可变参数
    public static void close(Closeable...ios) {
        for(Closeable io:ios) {
            try {
                if( io != null) io.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
### Java 中使用 IO 流实现文件拷贝Java 中,可以通过字节流或字符流来完成文件的复制工作。对于二进制文件(如图像、视频),应采用 `FileInputStream` 和 `FileOutputStream` 来执行读取和写入操作;而对于纯文本文件,则可以选择更高效的 `FileReader` 和 `FileWriter` 进行处理[^4]。 下面是一个利用字节流进行文件复制的具体实例: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileCopyExample { public static void main(String[] args) { String sourceFilePath = "source.txt"; String destinationFilePath = "destination.txt"; try (FileInputStream fis = new FileInputStream(sourceFilePath); FileOutputStream fos = new FileOutputStream(destinationFilePath)) { byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { fos.write(buffer, 0, length); } System.out.println("文件已成功复制!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 此代码片段展示了如何创建两个文件流对象——一个是用于源文件的输入流 (`FileInputStream`) ,另一个是目标文件的输出流(`FileOutputStream`). 接着定义了一个缓冲区数组,在循环体内不断从输入流中读取数据并将其写入到输出流直到整个文件被完全传输完毕[^1]. 当涉及到大容量的数据或者追求更高的性能时,建议增加缓存大小以减少磁盘I/O次数,并考虑关闭自动刷新功能以便手动控制何时将内容刷入目的地文件.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值