android文件,android之下載文件

 2023-11-30 阅读 30 评论 0

摘要:使用場景:用tomcat搭建了一個文件服務器,然后在安卓端去下載文件。 使用技術:使用 HttpURLConnection 建立http連接,并下載 package com.example.facecompare.FaceApi;import android.content.Context; import android.util.Log;import java.io.B

使用場景:用tomcat搭建了一個文件服務器,然后在安卓端去下載文件。

使用技術:使用 HttpURLConnection 建立http連接,并下載

package com.example.facecompare.FaceApi;import android.content.Context;
import android.util.Log;import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;public class ModelDownload {/** 獲取http連接處理類HttpURLConnection*/private HttpURLConnection getConnection(String strUrl){URL url;HttpURLConnection urlcon = null;try {url = new URL(strUrl);urlcon = (HttpURLConnection) url.openConnection();} catch (Exception e) {e.printStackTrace();}return urlcon;}/** 寫文件到sd卡 demo* 前提需要設置模擬器sd卡容量,否則會引發EACCES異常* 先創建文件夾,在創建文件*/public boolean down2sd(String strUrl, String filename, downhandler handler){HttpURLConnection urlcon = getConnection(strUrl);if (urlcon == null){return false;}File file = new File(filename);FileOutputStream outputStream = null;try {int currentSize =0;int totalSize =0;InputStream inputStream = urlcon.getInputStream();if (200 != urlcon.getResponseCode()){return false;}totalSize = urlcon.getContentLength();outputStream = new FileOutputStream(file);byte[] buffer = new byte[1024*10];while (true) {int iReadSize = inputStream.read(buffer);if (-1 == iReadSize){break;}outputStream.write(buffer,0,iReadSize);//同步更新數據currentSize = currentSize+iReadSize;handler.setSize(currentSize,totalSize);}inputStream.close();} catch (Exception e) {return false;} finally {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}return true;}/** 內部回調接口類*/public abstract static class downhandler{public abstract void setSize(int currentSize,int totalSize);}
}

使用方法:

                        ModelDownload load = new ModelDownload();load.down2sd("http://192.168.31.16:8080/download/"+modelName,storagePath,new ModelDownload.downhandler(){@Overridepublic void setSize(int currentSize, int totalSize) {item.put("DownState",currentSize+"/"+totalSize);Message mes = mHandle.obtainMessage();mes.what = 100;mHandle.sendMessage(mes);}});

?

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/185775.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息