我有以下代码片段,可将zip文件从互联网下载到我的SD卡。它以原始大小下载文件。但我无法提取文件,因为它显示“文件已损坏”错误。它发生在所有网址上。
URL url;
URLConnection conn;
int fileSize;
InputStream inStream;
String outFile;
String fileName = "";
OutputStream outStream;
Message msg;
msg = Message.obtain(mhandler, DOWNLOAD_STARTED, 0, 0, downloadUrl);
mhandler.sendMessage(msg);
try {
url = new URL(downloadUrl);
conn = url.openConnection();
if(url.getProtocol().equals("https")){
conn = (HttpsURLConnection) conn;
}
conn.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.addRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
fileSize = conn.getContentLength();
int fileSizeKB = fileSize / 1024;
msg = Message.obtain(mhandler, DOWNLOAD_STARTED, fileSizeKB, 0,
fileName);
mhandler.sendMessage(msg);
inStream = conn.getInputStream();
outFile = Environment.getDataDirectory().getPath()+"/windows/Documents/file.zip";
outStream = new FileOutputStream(outFile);
byte[] data = new byte[1024];
int bytesRead = 0;
while (!isInterrupted()
&& (bytesRead = inStream.read(data)) != -1) {
outStream.write(data, 0, bytesRead);
}
outStream.flush();
outStream.close();
inStream.close();
if (isInterrupted()) {
new File(outFile).delete();
} else {
msg = Message.obtain(mhandler, DOWNLOAD_COMPLETED);
mhandler.sendMessage(msg);
}
} catch (Exception exp) {
msg = Message.obtain(mhandler, DOWNLOAD_FAILED);
mhandler.sendMessage(msg);
}
你能告诉我我在做什么错吗?
答案 0 :(得分:1)
尝试使用此代码下载文件:
res.setHeader('Access-Control-Allow-Origin', '*');
答案 1 :(得分:0)
int mFileSize = 0;
String path = "/sdcard/path";
final int BUFFER_SIZE = 1024;
BufferedInputStream bis;
RandomAccessFile fos;
byte[] buf = new byte[BUFFER_SIZE];
int curPosition = 0;
File destFile = new File(path + File.separator + "fileName");
if(destFile.exists()) {
destFile.delete();
}
try {
URL url = new URL("http://xxx.xxx");
URLConnection conn = url.openConnection();
conn.setAllowUserInteraction(true);
mFileSize = conn.getContentLength();
if(mFileSize <= 0) {
if(destFile.exists()) {
destFile.delete();
}
return;
}
fos = new RandomAccessFile(destFile, "rw");
bis = new BufferedInputStream(conn.getInputStream());
while(curPosition < mFileSize) {
int len = bis.read(buf, 0, BUFFER_SIZE);
if (len == -1) {
break;
}
fos.write(buf, 0, len);
curPosition += len;
}
bis.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
if(destFile.exists()) {
destFile.delete();
}
}