aws s3 java sdk 下载 pdf 被损坏

发布于 2024-10-31 12:04:05 字数 602 浏览 0 评论 0原文

我正在使用 getObject api 从 aws s3 下载文件。简单的文本文件工作正常,但在下载 pdf 时我的文件已损坏。我正在使用 FileOutputStream 并将内容保存在文件中,但保存的 pdf 已损坏。

我不太确定用于此目的的正确 java api 以及读取的字节被写入的字节数组的大小应该是多少。

我也很好奇直接使用 SDK 是否有意义,或者 Java 中是否有我可以利用的开源包装 api。

FileOutputStream fout = new FileOutputStream(new File(destFileName));

 byte[] b = new byte[8192];
 int bytesRead;
    while (true) {
     bytesRead = input.read(b);
        System.out.println("bytesRead = "+bytesRead );
        if (bytesRead==-1) 
         break;
        fout.write(b);
    }        
    fout.flush();
    fout.close();

I am downloading files from aws s3 using the getObject api. Simple text files work fine, but on pdf download my file is corrupted. I am using FileOutputStream and saving contents in a file, but the pdf saved is getting corrupted.

I am not quite sure about the correct java api to use for this purpose and what should be the size of the byte array where the bytes read get written.

I am also curious if using the SDK directly makes sense, or is there are open source wrapper api's available in Java that I could be leveraging.

FileOutputStream fout = new FileOutputStream(new File(destFileName));

 byte[] b = new byte[8192];
 int bytesRead;
    while (true) {
     bytesRead = input.read(b);
        System.out.println("bytesRead = "+bytesRead );
        if (bytesRead==-1) 
         break;
        fout.write(b);
    }        
    fout.flush();
    fout.close();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紫﹏色ふ单纯 2024-11-07 12:04:05

老实说,我敢打赌问题在于您将整个缓冲区写入了 FileOutputStream。在传输结束时,缓冲区不会完全填满/覆盖,并且您最终会将上次读取留下的一些字节写入文件的末尾。您需要修改此代码以仅写入实际从输入流读取的字节数,而不是整个缓冲区。

如果您在上次读取期间只读取了 100 个字节,则无需

fout.write(b);

尝试

fout.write(b, 0, bytesRead);

这种方式,只需写入缓冲区的前 100 个字节,并忽略实际上已写入文件的剩余 8092 个字节。

To be honest with you, I'm willing to bet the problem is that you write the entire buffer to the FileOutputStream. At the end of the transmission, the buffer won't be completely full/overwritten and you will end up writing some bytes to the end of the file that were left over from the last read. You need to modify this code to only write the number of bytes that are actually read from the input stream, rather than the entire buffer.

Instead of

fout.write(b);

Try

fout.write(b, 0, bytesRead);

This way, if you only read 100 bytes during the last read, you only write the first 100 bytes of the buffer and ignore the remaining 8092 bytes that were actually already written to the file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文