Cannot transfer a file from one place to another using java codes
I am using somehting like below :
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(targerFile);
HttpResponse response = httpclient.execute(开发者_JS百科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?
use org.apache.http.util.EntityUtils:
byte[] data = EntityUtils.toByteArray(response.getEntity());
httpClient.getConnectionManager().shutdown();
write that bytearray to a file with FileUtils from commons-io:
FileUtils.writeByteArrayToFile(destinationFile, data);
do not close the streams inside the loop. do that outside the loop after the entire input stream is read.
it looks to me like you're closing your bytOut stream after 1 byte is read. But I would do something like this instead:
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
PrintWriter pw = new PrintWriter(new FileOutputStream(destinationFile));
while ((line = reader.readLine()) != null) pw.println(line);
pw.close();
reader.close();
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 a FileOutputStream
. Write directly to the file instead.
Third, use a byte[]
and BufferedInputStream
and BufferedOutputStream
so you read more bytes at a time.
Fourth, disregard the above and just use commons-io.
精彩评论