我將於茫茫人海中,訪我唯一靈魂之伴侶;得之 我幸 失之我命
阿新 • • 發佈:2018-12-30
廢話就不多說了直接看下怎麼實現
1.新增相關的許可權,裝置API大於6.0時需要主動申請許可權
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
//裝置API大於6.0時,主動申請許可權
private void requestPermission(Activity context) {
if (Build.VERSION .SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.WRITE _EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
}
}
2.連線伺服器獲取檔案
/**
* 從伺服器下載檔案
* @param path 下載檔案的地址
* @param FileName 檔名字
*/
public static void downLoad(final String path, final String FileName) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(5000);
con.setConnectTimeout(5000);
con.setRequestProperty("Charset", "UTF-8");
con.setRequestMethod("GET");
if (con.getResponseCode() == 200) {
InputStream is = con.getInputStream();//獲取輸入流
FileOutputStream fileOutputStream = null;//檔案輸出流
if (is != null) {
FileUtils fileUtils = new FileUtils();
fileOutputStream = new FileOutputStream(fileUtils.createFile(FileName));//指定檔案儲存路徑,程式碼看下一步
byte[] buf = new byte[1024];
int ch;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);//將獲取到的流寫入檔案中
}
}
if (fileOutputStream != null) {
fileOutputStream.flush();
fileOutputStream.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
3.建立檔案儲存路徑
public class FileUtils {
private String path = Environment.getExternalStorageDirectory().toString() + "/shidoe";
public FileUtils() {
File file = new File(path);
/**
*如果資料夾不存在就建立
*/
if (!file.exists()) {
file.mkdirs();
}
}
/**
* 建立一個檔案
* @param FileName 檔名
* @return
*/
public File createFile(String FileName) {
return new File(path, FileName);
}
}
4.下載示例
downLoad("http://www.shidoe.com/shidoe/Edition/upfile/04.png", "che.png");//下載完成後就可以在手機目錄裡檢視到了
5.動態獲取需要儲存檔案的檔名
//獲取 / 最後一次出現的位置,然後位置+1擷取剩餘的就是檔名了
String s = "http://www.shidoe.com/shidoe/Edition/upfile/04.png";
int i = s.lastIndexOf("/");
String FileName= s.substring(i + 1);
6.載入剛下載好的圖片顯示在介面上還是非常easy的
private void loadImage() {
String path = Environment.getExternalStorageDirectory().toString() + "/shidoe";
try {
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(new File(path, "che.png")));
iv.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}