BufferedInputStream / BufferedOutputStream 文件读取/写入的速度 复制文件将数据从任何来源复制到任何目的地InputStream to OutputStream输入流输出流

如何解决BufferedInputStream / BufferedOutputStream 文件读取/写入的速度 复制文件将数据从任何来源复制到任何目的地InputStream to OutputStream输入流输出流

有两个问题。

  1. 如果编码为 bis.read() 而不是 bis.read(bys),程序实际上会做什么? (无论如何它都可以工作,但速度要慢得多。)

  2. 为什么 bos.write(bys) 比 bos.write(bys,len) 快得多? (我预计两者在运行中的速度相同。)

谢谢!

public class CopyFileBfdBytes {

    public static void main(String[] args) throws IOException {

        FileInputStream fis = new FileInputStream("d:/Test1/M1.MP3");
        BufferedInputStream bis = new BufferedInputStream(fis);

        FileOutputStream fos = new FileOutputStream("d:/Test2/M2.mp3");
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] bys = new byte[8192];
        int len;
        while ((len = bis.read(bys)) != -1){
//        while ((len = bis.read()) != -1){  // 1. Why does it still work when bys in bis.read() is missing?
            bos.write(bys);
//            bos.write(bys,len);     // 2. Why is this slower than bos.write(bys)?
            bos.flush();
        }
        fis.close();
        bis.close();
        fos.close();
        bos.close();
    }
}

解决方法

首先,您似乎只想按原样复制文件。有更简单的方法(甚至可能是更高效的方法)来做到这一点。

其他复制数据的方法

复制文件

如果您需要的只是复制示例中的实际文件,您可以简单地使用:

package example;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class SO66024231 {

    public static void main(String[] args) throws IOException {
        Files.copy(Paths.get("d:/Test1/M1.MP3"),Paths.get("d:/Test2/M2.mp3"));
    }
}

这很可能是最容易描述的(例如,其他开发人员实际上看到了您想要做什么)并且可以由底层系统非常有效地完成。

将数据从任何来源复制到任何目的地(InputStream to OutputStream)

如果您需要将数据从任何 InputStream 传输到任何 OutputStream,您可以使用 InputStream#transferTo(OutputStream) 方法:

package example;

import java.io.*;

public class SO66024231 {

    public static void main(String[] args) throws IOException {
        try (InputStream fis = new FileInputStream("d:/Test1/M1.MP3")) {
            try (OutputStream fos = new FileOutputStream("d:/Test2/M2.mp3")) {
                fis.transferTo(fos);
            }
        }
    }
}

深入描述您的问题

注意:我将一般性地讨论 InputStreamOutputStream。您使用了 BufferedInputStreamBufferedOutputStream。这些是内部缓冲数据的特定实现。这个内部缓冲与我接下来要讲的缓冲无关!

输入流

InputStream#read()InputStream#read(byte[]) 之间存在根本区别。

InputStream#read() 从 InputStream 读取一个字节并返回它。如果 Stream 耗尽(没有更多数据),则返回值为 int0-255 范围内的 -1

package example;

import java.io.*;

public class SO66024231 {

    public static void main(String[] args) throws IOException {
        final byte[] myBytes = new byte[]{-1,3,4,5,6,7,8,127};
        printAllBytes(new ByteArrayInputStream(myBytes));
    }

    public static void printAllBytes(InputStream in) throws IOException {
        int currByte;
        while ((currByte = in.read()) != -1) {
            System.out.println((byte) currByte);// note the cast to byte!
        }
        
        // prints: -1,127
    }
}

InputStream#read(byte[]) 然而,完全不同。它采用 byte[] 作为参数,用作缓冲区。然后它(在内部)尝试用目前可以获得的尽可能多的字节填充给定的缓冲区,并返回它已填充的实际字节数或 -1(如果 Stream 是累死了。

示例:

package example;

import java.io.*;

public class SO66024231 {

    public static void main(String[] args) throws IOException {
        final byte[] myBytes = new byte[]{-1,127};
        printAllBytes(new ByteArrayInputStream(myBytes));
    }

    public static void printAllBytes(InputStream in) throws IOException {
        final byte[] buffer = new byte[2];// do not use this small buffer size. This is just for the example
        int bytesRead;

        while ((bytesRead = in.read(buffer)) != -1) {
            // loop from 0 to bytesRead,!NOT! to buffer.length!!!
            for (int i = 0; i < bytesRead; i++) {
                System.out.println(buffer[i]);
            }
        }

        // prints: -1,127
    }
}

不好的例子: 现在是一个不好的例子。以下代码包含编程错误,请勿使用!

我们现在从 0 循环到 buffer.length,但我们的输入数据正好包含 9 字节。这意味着,在最后一次迭代中,我们的缓冲区将只填充一个字节。我们缓冲区中的第二个字节不会被触及。

package example;

import java.io.*;

public class SO66024231 {

    /**
     * ERROURNOUS EXAMPLE!!! DO NOT USE
     */
    public static void main(String[] args) throws IOException {
        final byte[] myBytes = new byte[]{-1,127};
        printAllBytes(new ByteArrayInputStream(myBytes));
    }

    public static void printAllBytes(InputStream in) throws IOException {
        final byte[] buffer = new byte[2];// do not use this small buffer size. This is just for the example
        int bytesRead;

        while ((bytesRead = in.read(buffer)) != -1) {
            for (int i = 0; i < buffer.length; i++) {
                System.out.println(buffer[i]);
            }
        }

        // prints: -1,127,8 <-- see; the 8 is printed because we ignored the bytesRead value in our for loop; the 8 is still in our buffer from the previous iteration
    }
}

输出流

既然我已经描述了阅读的不同之处,我将向您描述写作的不同之处。

首先,正确的例子(使用OutputStream.write(byte[],int,int)):

package example;

import java.io.*;
import java.util.Arrays;

public class SO66024231 {

    public static void main(String[] args) throws IOException {
        final byte[] myBytes = new byte[]{-1,127};
        final byte[] copied = copyAllBytes(new ByteArrayInputStream(myBytes));

        System.out.println(Arrays.toString(copied));// prints: [-1,127]
    }

    public static byte[] copyAllBytes(InputStream in) throws IOException {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final byte[] buffer = new byte[2];
        int bytesRead;

        while ((bytesRead = in.read(buffer)) != -1) {
            bos.write(buffer,bytesRead);
        }

        return bos.toByteArray();
    }
}

还有一个不好的例子:

package example;

import java.io.*;
import java.util.Arrays;

public class SO66024231 {

    /*
    ERRORNOUS EXAMPLE!!!!
     */
    public static void main(String[] args) throws IOException {
        final byte[] myBytes = new byte[]{-1,8] <-- see; the 8 is here again
    }

    public static byte[] copyAllBytes(InputStream in) throws IOException {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final byte[] buffer = new byte[2];
        int bytesRead;

        while ((bytesRead = in.read(buffer)) != -1) {
            bos.write(buffer);
        }

        return bos.toByteArray();
    }
}

这是因为,就像在我们使用 InputStream 的示例中一样,如果我们忽略 bytesRead,我们将向 OutputStream 写入一个我们不想要的值:来自前一次迭代的字节 8。这是因为在内部,OutputStream#write(byte[])(在大多数实现中)只是 OutputStream.write(buffer,buffer.length) 的快捷方式。这意味着它会将整个缓冲区写入 OutputStream

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-