英文:
Converting OutputStream into PipedOutputstream
问题
在Java中,Function A中有一些现有的代码,它返回一个OutputStream,但我想让它返回一个PipedOutputStream,这样我就可以像这样使用PipedInputStream:
this.inputStream = new PipedInputStream(this.outputStream);
将OutputStream强制转换为PipedInputStream是否有效,还是我需要从头开始使用一个全新的PipedOutputStream并在那里重复所有逻辑?
更多代码:
我的PipedInputStream将像这样将数据传输到S3:
tm.upload(bucketName, objectKey, this.inputStream, objectMetadata);
(tm是TransferManager)
而PipedOutputStream将与一个写入文件的Writer一起使用。
OutputStream out = (encryptionKeyId != null) ?
pgpService.buildPgpOutputStream(this.outputStream, encryptionKeyId) :
this.outputStream;
return toBufferedWriter(out);
因此,在上面的开关语句中,当out
是this.outputStream
时,它运行良好,因为它是PipedOutputStream。但是pgpService.buildPgpOutputStream(this.outputStream, encryptionKeyId)
返回一个OutputStream,而不是PipedOutputStream,所以不太确定该怎么做。
英文:
In Java have some existing code in Function A that returns an OutputStream, but I'd like it to return a PipedOutputStream that I can use with a PipedInputStream like so:
this.inputStream = new PipedInputStream(this.outputStream);
Does casting an OutputStream to a PipedInputStream work, or do I need to begin with a fresh new PipedOutputStream and repeat all the logic there?
More Code:
my PipedInputStream will be transferring data to s3 like this:
tm.upload(bucketName, objectKey, this.inputStream, objectMetadata);
(tm is the TransferManager)
and the PipedOutputStream will be with a Writer that writes to files.
OutputStream out = (encryptionKeyId != null) ?
pgpService.buildPgpOutputStream(this.outputStream, encryptionKeyId) :
this.outputStream;
return toBufferedWriter(out);
So in the switch above, when out
is this.outputStream;
, it's working fine. because it's PipedOutputStream. but pgpService.buildPgpOutputStream(this.outputStream, encryptionKeyId)
returns an OutputStream, not a Piped one, so not sure what to do.
答案1
得分: 1
你不需要做任何事情。
你构建的bufferedWriter
最终会写入this.outputStream
,这是你的管道输出流。你不需要对它进行强制转换或其他操作 - 你已经在你的类的实例变量中有对管道两端的引用。我假设你的代码看起来像下面这样。
this.outputStream = new PipedOutputStream();
this.inputStream = new PipedInputStream(this.outputStream);
OutputStream out = (encryptionKeyId != null) ?
pgpService.buildPgpOutputStream(this.outputStream, encryptionKeyId) :
this.outputStream;
return toBufferedWriter(out);
英文:
You don't need to do anything.
The bufferedWriter
that you build, eventually writes to this.outputStream
which is your piped output stream. You don't need to cast it or do anything with it - you already have a reference to both ends of the pipe in the instance variables of your class. I'm assuming your code looks like the following.
this.outputStream = new PipedOutputStream();
this.inputStream = new PipedInputStream(this.outputStream);
OutputStream out = (encryptionKeyId != null) ?
pgpService.buildPgpOutputStream(this.outputStream, encryptionKeyId) :
this.outputStream;
return toBufferedWriter(out);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论