java如何在sd上写入文件时获得文件大小?
请帮帮我。我需要得到完整的文件大小,并且已经写入while循环。我需要这个来设置进度条的进度。 这是我的代码:
try {
URL u = new URL(imgUrl);
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "saved" + File.separator);
root.mkdirs();
String name = "" + System.currentTimeMillis() + ".jpg";
File sdImageMainDirectory = new File(root, name);
Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);
OutputStream output = new FileOutputStream(sdImageMainDirectory);
while ((length = dis.read(buffer))>0) {
output.write(buffer, 0, length);
}
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
}
# 1 楼答案
如果您想获得已经写入的字节数,请使用以下方法:
在while循环之前添加一个名为
writtenBytes
的变量:然后,在while循环中,添加以下代码:
要在下载文件之前获得文件大小,您必须将下载代码更改为: