java中的简单流读/写问题 [英] Simple stream read/write question in java
问题描述
我正在尝试通过URLConnection上传文件,但我需要将其作为二进制文件读/写而不进行任何编码更改。
I'm trying to upload a file via URLConnection, but I need to read/write it as a binary file without any encoding changes.
所以我已经试图从 FileInputStream
中读取 byte []
数组,但现在我遇到了问题。我用来输出到服务器的 PrintWriter
对象不允许我做 writer.write(content)
(其中 content
的类型为 byte []
)。我怎样才能解决这个问题?或者是否有另一种方法可以快速将二进制数据从 FileInputStream
复制到 PrintWriter
?
So i've tried to read byte[]
array from a FileInputStream
, but now i have an issue. The PrintWriter
object I use for outputing to the server does not allow me to do writer.write(content)
(where content
is of type byte[]
). How can i fix this? Or is there another way to quickly copy binary data from a FileInputStream
to a PrintWriter
?
谢谢
推荐答案
Writer
对象(包括 PrintWriter
)专门用于输出字符数据。听起来你想要一个 OutputStream
而不是 Writer
这里。
你的 PrintWriter
来自哪里?如果它是通过使用 OutputStreamWriter
包装某种 OutputStream
创建的,然后使用 PrintWriter
,那么你应该只使用原来的 OutputStream中的原始
,而不是尝试使用 write(byte [] b)
方法 Writer
。
Where did your PrintWriter
come from? If it was created by wrapping some kind of OutputStream
with an OutputStreamWriter
and then wrapping that with a PrintWriter
, then you should just use the original write(byte[] b)
method from the original OutputStream
, rather than trying to use a Writer
.
如果你想混合字符输出和字节输出,您可能需要使用 String.getBytes()
。看看这个例子:
If you want to mix character output and byte output, you may need to use String.getBytes()
. Check out this example:
OutputStream o = this.conn.getOutputStream(); // Based on your comment
String s = "Hello, world!";
byte[] b = ...; // These are the raw bytes that you want to write
o.write(s.getBytes("UTF-8"));
o.write(b);
(当然,只有在阅读输出的系统明白您正在撰写时,这才有效字符和原始字节的混合,并知道如何处理您发送它的混合数据。)
(Of course, this will only work if the system that is reading your output understands that you are writing a mixture of characters and raw bytes and knows how to handle the mixed data that you are sending it.)
这篇关于java中的简单流读/写问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!