gpt4 book ai didi

java - writeTo PipedOutputStream 只是挂起

转载 作者:行者123 更新时间:2023-11-30 08:32:08 26 4
gpt4 key购买 nike

我的目标是:

  1. 从 S3 读取文件,
  2. 更改其元数据
  3. 再次推送到S3

AWS java SDK 不允许推送输出流。因此,我必须将 outputstream 从 step2 转换为 inputstream。为此,我决定使用 PipedInputStream

但是,我的代码只是卡在 writeTo(out); 这一步。此代码位于 grails 应用程序中。代码挂起时CPU不是高耗:

import org.apache.commons.imaging.formats.jpeg.xmp.JpegXmpRewriter;

AmazonS3Client client = nfile.getS3Client() //get S3 client
S3Object object1 = client.getObject(
new GetObjectRequest("test-bucket", "myfile.jpg")) //get the object.

InputStream isNew1 = object1.getObjectContent(); //create input stream
ByteArrayOutputStream os = new ByteArrayOutputStream();
PipedInputStream inpipe = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(inpipe);

try {
String xmpXml = "<x:xmpmeta>" +
"\n<Lifeshare>" +
"\n\t<Date>"+"some date"+"</Date>" +
"\n</Lifeshare>" +
"\n</x:xmpmeta>";/
JpegXmpRewriter rewriter = new JpegXmpRewriter();
rewriter.updateXmpXml(isNew1,os, xmpXml); //This is step2

try {
new Thread(new Runnable() {
public void run () {
try {
// write the original OutputStream to the PipedOutputStream
println "starting writeto"
os.writeTo(out);
println "ending writeto"
} catch (IOException e) {
// logging and exception handling should go here
}
}
}).start();

ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(1024); //just testing
client.putObject(new PutObjectRequest("test-bucket", "myfile_copy.jpg", inpipe, metadata));
os.writeTo(out);

os.close();
out.close();
} catch (IOException e) {
// logging and exception handling should go here
}

}
finally {
isNew1.close()
os.close()
out.close()
}

上面的代码只是打印starting writeto 并挂起。它不打印 ending writeto

更新通过将 writeTo 放在一个单独的线程中,文件现在正在写入 S3,但是,只写入了其中的 1024 个字节。文件不完整。我如何编写从输出流到 S3 的所有内容?

最佳答案

当你执行 os.writeTo(out) 时,它会尝试将整个流刷新到out,并且由于还没有人从它的另一端(即 inpipe)读取,内部缓冲区填满,线程停止。

您必须在写入数据之前设置读取器,并确保它在单独的线程中执行(请参阅 PipedOutputStream 上的 javadoc)。

关于java - writeTo PipedOutputStream 只是挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40270375/

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