我正在尝试从InputStream
读取数据,并使用RandomAccessFile
将其写入sdcard。我想实现下载速度。所以我认为,从RandomAccessFile
获得写作速度是实现这一目标的最佳方式。这是我的代码:
long downloaded = 0;
status = DOWNLOADING;
URL url = new URL(requestUrl);
try {
String extStorage = Environment.getExternalStorageDirectory().getPath();
String file = extStorage+"/abc.zip";
RandomAccessFile output = new RandomAccessFile(file, "rw");
System.setProperty("http.keepAlive", "false");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
connection.connect();
long fileLength = connection.getContentLength();
InputStream stream = connection.getInputStream();
while (status == DOWNLOADING) {
byte buffer[] = new byte[1024];
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1)
break;
// Write buffer to file. I need to get this writing speed.
output.write(buffer, 0, read);
downloaded += read;
}
output.close();
stream.close();
}
如何从RandomAccessFile
以KB /秒为单位获得写入速度?
或者,您有什么想法吗?
感谢您的帮助。
答案 0 :(得分:0)
你可以从一个类似于此的东西中得到一个粗略的东西:
开始每隔一秒调用一次runnable
。
在课堂上有
private static int bytesWritten = 0;
private static int kbPerSec = 0;
runnable
内部有类似
kbPerSec = bytesWritten / 1000;
bytesWritten = 0;
//Do with the result what you want
稍微修改你的while循环
kbPerSec = 0;
bytesWritten = 0;
//Start runnable
while (status == DOWNLOADING) {
byte buffer[] = new byte[1024];
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1)
break;
// Write buffer to file. I need to get this writing speed.
output.write(buffer, 0, read);
//Keep track of how much has been written since the last time the runnable was called
bytesWritten += read;
downloaded += read;
}
//Stop runnable