Android从本地选择文件并判断文件类型并获取选到文件大小的方法

来源:互联网 发布:红蚁网络运维 编辑:程序博客网 时间:2024/05/21 13:57

最近有一个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这个方法

@Overrideprotected 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;}



0 0
原创粉丝点击