代码拉取完成,页面将自动刷新
importClass("java.io.FileOutputStream");
importClass("java.io.InputStream");
importClass("java.net.URL");
importClass("java.net.URLConnection");
function download(url, path, possibleSize) {
let isOk = true;
files.ensureDir(path);
let fs = new FileOutputStream(path);
let conn = new URL(url).openConnection();
let isOver = false;
let inStream;
try {
inStream = conn.getInputStream();
let buffer = util.java.array("byte", 1024);
let contentLength = conn.getContentLength();
if (contentLength > 0) {
toastLog("开始下载,文件总大小:" + unitConvert(contentLength));
} else if (possibleSize > 0) {
toastLog("开始下载,文件大小未知\n预计大小:" + unitConvert(possibleSize));
} else {
toastLog("开始下载,文件大小未知");
}
let currentLength = 0;
threads.start(
function() {
while (true) {
sleep(3000);
if (isOver) {
break;
}
let perStr = "";
if (contentLength > 0) {
let percent = currentLength / contentLength * 100;
perStr = percent.toFixed(2);
toastLog("已下载" + perStr + "%\n大小:" + unitConvert(currentLength));
} else if (possibleSize > 0) {
let percent = currentLength / possibleSize * 100;
perStr = percent.toFixed(2);
toastLog("大约已下载" + perStr + "%(不准确)\n大小:" + unitConvert(currentLength));
} else {
toastLog("已下载大小:" + unitConvert(currentLength));
}
}
}
);
while (true) {
let length = inStream.read(buffer);
if (length === -1) {
toastLog("下载完成!");
break;
}
currentLength += length;
fs.write(buffer, 0, length);
}
fs.close();
} catch (e) {
isOk = false;
toastLog("下载发生错误\n" + e);
fs.close();
files.remove(path)
}
isOver = true;
return isOk;
}
function unitConvert(length) {
if (length < 1024) {
return length + " B";
} else if (length < 1024 * 1024) {
return (length / 1024).toFixed(2) + " KB";
} else {
return (length / 1024 / 1024).toFixed(2) + " MB";
}
}
module.exports = download;
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。