侧边栏壁纸
博主头像
Epoch

Java开发、Python爬虫、微服务、分布式、前端

  • 累计撰写 94 篇文章
  • 累计创建 111 个标签
  • 累计收到 8 条评论

目 录CONTENT

文章目录

Java字节流复制文件

Epoch
2021-01-20 / 0 评论 / 0 点赞 / 326 阅读 / 408 字 / 正在检测是否收录...

Java字节流复制文件

普通字节流

package com.xmaven;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @ClassName FileInputDemo
 * @Description TODO
 * @Author Ambition
 * @Date 2021/1/20 15:39
 * @Version 1.0.0
 **/
public class FileInputDemo {
    public static void main(String[] args) {
        try {
        	// 定义读取的文件
            FileInputStream fis = new FileInputStream("test.txt");
            // 定义输出的文件
            FileOutputStream fos = new FileOutputStream("testcopy.txt");
            int n = 0;
            // 定义缓冲区
            byte[] b = new byte[1024];
            // 判断是否获取到文件的末尾  -1表示读取到文件末尾
            while ((n = fis.read(b)) != -1) {
            	// 第一个参数写入的数据
            	// 第二个参数数据中的起始偏移量
            	// 第三个参数要写入的字节数
                fos.write(b, 0, n);
            }
            fos.close();
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

缓冲字节流

package com.xmaven;

import java.io.*;

/**
 * @ClassName BufferedDemo
 * @Description TODO
 * @Author Ambition
 * @Date 2021/1/20 15:48
 * @Version 1.0.0
 **/
public class BufferedDemo {
    public static void main(String[] args) {
        try {
        	// 定义读取的源文件
            FileInputStream fis = new FileInputStream("test.txt");
            // 放入到缓冲字输入节流中
            BufferedInputStream bis = new BufferedInputStream(fis);
            // 定义一个输出的文件
            FileOutputStream fos = new FileOutputStream("testcopy.txt");
            // 把这个文件放入到缓冲字输出节流中
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            int n = 0;
            byte[] b = new byte[1024];
            while ((n = bis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            /*
            * flush()方法主要用来清空缓冲区。当缓冲区被填满时就会自动执行写操作,但是当缓冲区不满时,
            * 就不会执行写操作。所以,当缓冲区未被填满但要执行写操作时就要强制清空缓冲区
            * */
            bos.flush();
            bos.close();
            fos.close();
            bis.close();
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
0

评论区