IO流4、IO流_节点流_字节流的使用

文件流——字节流的使用

  1. 对于文本文件(.txt/.java/.c/.cpp等)使用字符流处理
  2. 对于非文本文件(.jpg/.mp3/.mp4/.avi/.doc/.ppt等)使用字节流处理

!基本操作和字符流差不多!

  1. File类的实例化
  2. 流的实例化
  3. 读/写操作
  4. 关闭资源

读取:

@Test
public void testFileInputStream() {
    FileInputStream fileInputStream = null;
    try {
        //1、造文件
        File file = new File("hello.txt");
        //2、造流
        fileInputStream = new FileInputStream(file);
        //3、读数据
        byte[] buffer = new byte[5];
        int len;    //记录每次读取的字节的个数
        while ((len = fileInputStream.read(buffer)) != -1){
            String str = new String(buffer, 0, len);
            System.out.print(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

复制视频:

@Test
public void testCopyFile(){
    long start = System.currentTimeMillis();

    String srcPath = "E:\\Java自学笔记\\JavaSE\\6、IO流\\test1.avi";
    String destPath = "E:\\Java自学笔记\\JavaSE\\6、IO流\\test1_copy_1.avi";
    copyFile(srcPath, destPath);

    long end = System.currentTimeMillis();

    System.out.println("复制操作花费的时间为:" + (end - start));

}


//指定路径下文件的复制
public void copyFile(String srcPath, String destPath){
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
         File srcFile = new File(srcPath);
         File destFile = new File(destPath);
         fis = new FileInputStream(srcFile);
         fos = new FileOutputStream(destFile);
         byte[] bytes = new byte[1024];
         int len;
         while ((len = fis.read(bytes)) != -1){
            fos.write(bytes, 0, len);
        }
    } catch (IOException e) {
         e.printStackTrace();
    } finally {
        try {
            if (fis != null)
                fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
posted @ 2021-11-19 23:56  叁玖贰拾柒  阅读(32)  评论(0)    收藏  举报