我正在将mp3文件下载到SD卡。有时,当网络连接不良或互联网不可用时,ByteArrayOutputStream写入功能会继续运行,即使互联网可用,下载也不会恢复。我想在互联网丢失时抛出超时异常,但OutputStream本身不提供超时机制。如何在互联网不可用时停止写字节。 以下是我正在使用的代码 -
try {
URL url = new URL(downloadSongsList.get(count1).getTitle_Url());
URLConnection conection = url.openConnection();
conection.setRequestProperty("Range", "byte BHs=" + total + "-");
conection.connect();
//TODO: getting file length
int lenghtOfFile = conection.getContentLength();
//TODO: input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
int bytesRead;
data = new byte[lenghtOfFile];
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = input.read(data)) != -1) {
total += bytesRead;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, bytesRead);
}
//encrypt = simpleCrypto.encrypt(ENCRIPT_DECRIPT_KEY, data);
input.close();
encriptFile(output.toByteArray());
output.flush();
output.close();
success = "1";
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
success = "0";
startTimer();
}