关于IO流1

1.IO流按流向分类为输入流跟输出流
2.IO按操作单元划分为字节流跟字符流,1字符=2字节
3.按流的角色划分为节点流跟处理流
4.IO中抛出IOException后可以不用抛出FileNotFoundException
5.流的传输:byte[]在FileInputStream中的使用可以定义传输数据的大小
6.FileInputStream的skip()方法用于跳过不传输的字符

5.例:
FileInputStream fis = new FileInputStream(inputPath);
FileOutputStream fos = new FileOutputStream(outputPath);
byte[] bytes = new byte[1024];//设置字节数组的大小1024相当于设置每次传输数据的大小,1024为1Kb
while(fis.available()>0){//available方法返回的是剩余未读数据的大小
fis.read(bytes);
fos.write(bytes);
}
fis.close();//传输完之后一定要关闭它们
fos.close();
package study02;

import java.io.*;
import java.util.Scanner;

public class IOTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要拷贝文件的路径(包括文件名,例如E:/a.mp4)");
        String inputPath = sc.next();
        System.out.println("请输入拷贝文件的输出路径(包括文件名,例如E:/a/a.mp4)");
        String outputPath = sc.next();
        File file = new File(inputPath);
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(inputPath);
            outputStream = new FileOutputStream(outputPath);
            byte[] bytes = new byte[1024*100];//字节数组的长度,用于传输数据
            long length = file.length();
            int len;
            long copy = 0;
            long count = 0;
            long copied = 0;
            while ((len = inputStream.read(bytes))>0){//将读到的数据已字节的形式存储到byte数组中
                //读到多少写多少,防止因字节数组过大而写入空的数据
                outputStream.write(bytes,0,len);
                copy += len;//写入的进度
                copied = copy* 100 /length;//写入的百分比进度
                if (count+10<=copied){//每百分之十打印一次
                    System.out.println("复制进度" + copied + "%");
                    count = copied;//让新的进度覆盖老的进度
                }
            }
            outputStream.flush();//将内存中残余的数据写入到输出路径中
        } catch (FileNotFoundException e){//抛出文件未找到异常
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null){//关闭输入流
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null){//关闭输出流
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

posted @ 2021-03-09 18:55  温柔Rarry  阅读(57)  评论(0)    收藏  举报