写完后读取InputStream

时间:2014-04-19 11:14:20

标签: android inputstream httpurlconnection outputstream urlconnection

我在将输出流写入InputStream后尝试阅读sdcard。我已从HttpURLConnection下载了文件。文件成功写入sdcard。但我试图从inputstream读取same file,但内容未正确阅读。在emulator上显示了一些内容,但未显示on actual device内容。你能帮忙解决一下这个问题吗?我发布了downloadingwritingreading code

fileUrl = new URL(filename);
HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
InputStream is = connection.getInputStream();

/**
* Create file with input stream
*/
File downloadFile = new File("/sdcard/", "myFile3.pdf");
downloadFile.createNewFile();
final FileOutputStream outputStream = new FileOutputStream(downloadFile);

int availbleLength = is.available();
byte[] bytes = new byte[availbleLength];
int len1 = 0;
while ((len1 = is.read(bytes)) > 0) {
    outputStream.write(bytes, 0, len1);
}
outputStream.flush();
outputStream.close();

File myFile = new File("/sdcard/myFile3.pdf");
InputStream inputStream = new FileInputStream(myFile);

byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
System.out.println("Byte Lenght: " + buffer.length);

1 个答案:

答案 0 :(得分:0)

inputStream.available()只是估计而不是完整输入数据的实际长度。

FileInputStream.available()