Android從本地選擇檔案並判斷檔案型別並獲取選到檔案大小的方法
阿新 • • 發佈:2019-01-09
最近有一個android選擇本地檔案的並判斷檔案型別的需求
首先要選擇檔案通過點選事件進入到檔案列表 這裡是瀏覽所有的檔案。用到的是startActivityForResult
Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 1);
然後在這個頁面重寫onActivytResult這個方法
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { if (data != null) { final Uri uri = data.getData(); String path = getPath(this, uri); /*這裡要呼叫這個getPath方法來能過uri獲取路徑不能直接使用uri.getPath。 因為如果選的圖片的話直接使用得到的path不是圖片的本身路徑*/ File file = new File(path); /* 取得副檔名 */ String end = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length()).toLowerCase(); /*依副檔名的型別決定MimeType 這裡只用了pdf word 圖片更型別可查http://www.cnblogs.com/hibraincol/archive/2010/09/16/1828502.html*/ if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) { try {//圖片 String daxiao = FormentFileSize(getFileSizes(file));//獲取檔案大小的方法 fileDatas.add(new FilesParam(daxiao, path, file.getName())); Hadapter.notifyDataSetChanged();//更新listview顯示本圖片 } catch (Exception e) { e.printStackTrace(); } } else if (end.equals("doc")) { try {//word String daxiao = FormentFileSize(getFileSizes(file)); fileDatas.add(new FilesParam(daxiao, "DOC", file.getName())); Hadapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); } } else if (end.equals("pdf")) { try {//pdf String daxiao = FormentFileSize(getFileSizes(file)); fileDatas.add(new FilesParam(daxiao, "PDF", file.getName())); Hadapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); } } else if (end.equals("txt")) { try {//text String daxiao = FormentFileSize(getFileSizes(file)); fileDatas.add(new FilesParam(daxiao, "DOC", file.getName())); Hadapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(this, "只能選擇圖片、文件、PDF三種格式", Toast.LENGTH_SHORT).show(); } }
} }
下面是上面中提到的獲取檔案路徑和檔案大小的方法。值得注意的是在Android4.4以前可以通過data.getpath()來直接得到檔案路徑,但是4.4以後通過這個方法得到是路徑不是正確路徑(這裡說的是圖片)所以我們用下面getPath()方法來解決這個問題。別外在6.0版本以後讀寫檔案要有執行時許可權
//得到正確路徑 public static String getPath(Context context, Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;//sdk版本是否大於4.4 // DocumentProvider if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } // TODO handle non-primary volumes }else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId( Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[]{ split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null;}
下面這些是getPath中要呼叫的方法
public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri.getAuthority()); } public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri.getAuthority()); } public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri.getAuthority()); } public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri.getAuthority()); } public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = {column}; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int index = cursor.getColumnIndexOrThrow(column); return cursor.getString(index); } } finally { if (cursor != null) cursor.close(); } return null; }
/*得到傳入檔案的大小*/ public static long getFileSizes(File f) throws Exception { long s = 0; if (f.exists()) { FileInputStream fis = null; fis = new FileInputStream(f); s = fis.available(); fis.close(); } else { f.createNewFile(); System.out.println("資料夾不存在"); } return s; } /** * 轉換檔案大小成KB M等 */ public static String FormentFileSize(long fileS) { DecimalFormat df = new DecimalFormat("#.00"); String fileSizeString = ""; if (fileS < 1024) { fileSizeString = df.format((double) fileS) + "B"; } else if (fileS < 1048576) { fileSizeString = df.format((double) fileS / 1024) + "K"; } else if (fileS < 1073741824) { fileSizeString = df.format((double) fileS / 1048576) + "M"; } else { fileSizeString = df.format((double) fileS / 1073741824) + "G"; } return fileSizeString; }