无法使用java代码将文件从一个地方传输到另一个地方
我正在使用如下所示的内容:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(targerFile);
HttpResponse response = httpclient.execute(httpGet);
// get the response body as an array of bytes
HttpEntity entity = response.getEntity();
// write for the destination file
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
ByteArrayOutputStream bytOut = new ByteArrayOutputStream();
int x;
do {
x = instream.read();
if (x != -1) {
bytOut.write(x);
instream.close();
bytOut.close();
}
} while (x != -1);
FileOutputStream fout = new FileOutputStream(destinationFile);
fout.write(bytOut.toByteArray());
fout.close();
但只有那时我才发现来自 httpclient 的输入流已关闭。所以我无法多次阅读它。有什么解决办法吗?或者这不是正确的方法?
I am using somehting like below :
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(targerFile);
HttpResponse response = httpclient.execute(httpGet);
// get the response body as an array of bytes
HttpEntity entity = response.getEntity();
// write for the destination file
InputStream instream = null;
if (entity != null) {
instream = entity.getContent();
ByteArrayOutputStream bytOut = new ByteArrayOutputStream();
int x;
do {
x = instream.read();
if (x != -1) {
bytOut.write(x);
instream.close();
bytOut.close();
}
} while (x != -1);
FileOutputStream fout = new FileOutputStream(destinationFile);
fout.write(bytOut.toByteArray());
fout.close();
but only then i find out the inputstream from httpclient comes closed. so there is no way i can read it more than once. is there any work around for this? or is this not the correct way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 org.apache.http.util.EntityUtils:使用
commons-io 中的 FileUtils 将该字节数组写入文件:
use org.apache.http.util.EntityUtils:
write that bytearray to a file with FileUtils from commons-io:
不要关闭循环内的流。读取整个输入流后,在循环外部执行此操作。
do not close the streams inside the loop. do that outside the loop after the entire input stream is read.
在我看来,您在读取 1 个字节后关闭了 bytOut 流。但我会做这样的事情:
it looks to me like you're closing your bytOut stream after 1 byte is read. But I would do something like this instead:
首先,您的问题是在读取第一个字节后关闭循环中的输入流。不要那样做。
其次,如果您要做的只是将其写入
FileOutputStream
,则写入 ByteArrayOutputStream 是没有意义的。而是直接写入文件。第三,使用
byte[]
和BufferedInputStream
和BufferedOutputStream
以便一次读取更多字节。第四,忽略上述内容,仅使用 commons-io。
First, your problem is that you're closing the input stream in the loop after the first byte is read. Don't do that.
Second, there is no point in writing to a
ByteArrayOutputStream
if all you're going to do is to just write it to aFileOutputStream
. Write directly to the file instead.Third, use a
byte[]
andBufferedInputStream
andBufferedOutputStream
so you read more bytes at a time.Fourth, disregard the above and just use commons-io.