gpt4 book ai didi

java - 从不同于网络(通过 Amazon S3)的本地文件读取 InputStream 对象有何不同?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:52 25 4
gpt4 key购买 nike

我不认为从本地文件读取的输入流对象与从网络源(在本例中为 Amazon S3)读取的输入流对象之间没有区别,所以希望有人能启发我。

这些程序在运行 Centos 6.3 的虚拟机上运行。两种情况下的测试文件都是10MB。

本地文件代码:

    InputStream is = new FileInputStream("/home/anyuser/test.jpg");

int read = 0;
int buf_size = 1024 * 1024 * 2;
byte[] buf = new byte[buf_size];

ByteArrayOutputStream baos = new ByteArrayOutputStream(buf_size);

long t3 = System.currentTimeMillis();
int i = 0;
while ((read = is.read(buf)) != -1) {
baos.write(buf,0,read);
System.out.println("reading for the " + i + "th time");
i++;
}
long t4 = System.currentTimeMillis();
System.out.println("Time to read = " + (t4-t3) + "ms");

这段代码的输出是这样的:它读取了 5 次,这是有意义的,因为读入的缓冲区大小是 2MB,而文件是 10MB。

reading for the 0th time
reading for the 1th time
reading for the 2th time
reading for the 3th time
reading for the 4th time
Time to read = 103ms

现在,我们使用相同的 10MB 测试文件运行相同的代码,除了这次,源来自 Amazon S3。在完成从 S3 获取流之前,我们不会开始读取。然而,这一次,读取循环运行了数千次,而它应该只读取 5 次。

    InputStream is;
long t1 = System.currentTimeMillis();
is = getS3().getFileFromBucket(S3Path,input);
long t2 = System.currentTimeMillis();

System.out.print("Time to get file " + input + " from S3: ");
System.out.println((t2-t1) + "ms");

int read = 0;
int buf_size = 1024*1024*2;
byte[] buf = new byte[buf_size];

ByteArrayOutputStream baos = new ByteArrayOutputStream(buf_size);
long t3 = System.currentTimeMillis();
int i = 0;

while ((read = is.read(buf)) != -1) {
baos.write(buf,0,read);
if ((i % 100) == 0)
System.out.println("reading for the " + i + "th time");
i++;
}
long t4 = System.currentTimeMillis();

System.out.println("Time to read = " + (t4-t3) + "ms");

输出如下:

Time to get file test.jpg from S3: 2456ms
reading for the 0th time
reading for the 100th time
reading for the 200th time
reading for the 300th time
reading for the 400th time
reading for the 500th time
reading for the 600th time
reading for the 700th time
reading for the 800th time
reading for the 900th time
reading for the 1000th time
reading for the 1100th time
reading for the 1200th time
reading for the 1300th time
reading for the 1400th time
Time to read = 14471ms

读取流所花费的时间在每次运行时都会发生变化。有时需要 60 秒,有时需要 15 秒。它不会比 15 秒更快。在程序的每次测试运行中,读取循环仍然循环 1400 多次,尽管我认为它应该只有 5 次,就像本地文件示例一样。

当源通过网络时,即使我们已经完成从网络源获取文件,输入流也是这样工作的吗?预先感谢您的帮助。

最佳答案

我不认为它是java特有的。当您从网络读取时,无论您分配的缓冲区有多大,对操作系统的实际读取调用都会一次返回一个数据包。如果您检查读取数据的大小(您的读取变量),它应该显示所使用的网络数据包的大小。

这就是人们使用单独的线程从网络读取并通过使用异步 i/o 技术避免阻塞的原因之一。

关于java - 从不同于网络(通过 Amazon S3)的本地文件读取 InputStream 对象有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13353789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com