package com.basic.security.utils;
|
|
import android.content.ContentResolver;
|
import android.content.Context;
|
import android.database.Cursor;
|
import android.net.Uri;
|
import android.os.Build;
|
import android.os.Environment;
|
import android.provider.DocumentsContract;
|
import android.provider.MediaStore;
|
import android.util.Log;
|
|
import com.basic.security.base.BaseApplication;
|
|
import java.io.File;
|
import java.io.FileNotFoundException;
|
import java.io.InputStream;
|
//import io.reactivex.Observable;
|
//import io.reactivex.ObservableEmitter;
|
//import io.reactivex.ObservableOnSubscribe;
|
//import io.reactivex.Observer;
|
//import io.reactivex.android.schedulers.AndroidSchedulers;
|
//import io.reactivex.disposables.Disposable;
|
//import io.reactivex.schedulers.Schedulers;
|
|
/**
|
* Created by EN on 2016/8/27.
|
*/
|
public class FileUtils {
|
public static File getCacheDir() {
|
File file = BaseApplication.getApplication().getCacheDir();
|
return getDir(file);
|
}
|
|
public static File getFilesDir() {
|
File file = BaseApplication.getApplication().getFilesDir();
|
return getDir(file);
|
}
|
|
public static File getExternalCacheDir() {
|
File file = null;
|
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
|
file = BaseApplication.getApplication().getExternalCacheDir();
|
}
|
return getDir(file);
|
}
|
|
public static File getExternalFilesDir() {
|
File file = null;
|
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
|
file = BaseApplication.getApplication().getExternalFilesDir(null);
|
}
|
return getDir(file);
|
}
|
|
public static File getExternalStorageDir() {
|
File file = null;
|
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
|
file = Environment.getExternalStorageDirectory();
|
}
|
return getDir(file);
|
}
|
|
public static File getExternalStoragePublicDir(String type) {
|
File file = null;
|
// DIRECTORY_MUSIC, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES, DIRECTORY_ALARMS,
|
// DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES, DIRECTORY_MOVIES, DIRECTORY_DOWNLOADS,
|
// DIRECTORY_DCIM, or DIRECTORY_DOCUMENTS
|
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
|
file = Environment.getExternalStoragePublicDirectory(type);
|
}
|
return getDir(file);
|
}
|
|
public static File getDir(File file) {
|
if (file == null) {
|
return null;
|
}
|
if (file.isFile()) {
|
file.delete();
|
}
|
if (!file.exists()) {
|
file.mkdir();
|
}
|
return file;
|
}
|
|
//小米手机不可用
|
public static String getPath(Context context, Uri uri) {
|
if ("content".equalsIgnoreCase(uri.getScheme())) {
|
String[] projection = {"_data"};
|
Cursor cursor = null;
|
try {
|
cursor = context.getContentResolver().query(uri, null, null, null, null);
|
String cs[] = cursor.getColumnNames();
|
int i = 0;
|
cursor.moveToFirst();
|
for (String s : cs) {
|
Log.i("column", s + ":" + cursor.getString(i));
|
if ("_data".equals(s)) {
|
return cursor.getString(i);
|
} else if ("document_id".equals(s)) {
|
String path = cursor.getString(i);
|
if (path.startsWith("raw:")) {
|
return cursor.getString(i).split(":")[1];
|
}
|
}
|
i++;
|
}
|
int column_index = cursor.getColumnIndexOrThrow("_data");
|
if (cursor.moveToFirst()) {
|
return cursor.getString(column_index);
|
}
|
} catch (Exception e) {
|
// Eat it Or Log it.
|
} finally {
|
if (!cursor.isClosed()) {
|
cursor.close();
|
}
|
}
|
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
|
return uri.getPath();
|
}
|
return null;
|
}
|
|
public static InputStream getInputStream(Context context, Uri uri) {
|
try {
|
return context.getContentResolver().openInputStream(uri);
|
} catch (FileNotFoundException e) {
|
e.printStackTrace();
|
}
|
return null;
|
}
|
|
public static String getPathFormUri(Uri uri) {
|
String path;
|
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
|
path = getPath(uri);
|
} else {
|
path = getRealPathFromURI(uri);
|
}
|
return path;
|
}
|
|
// public static void writeFile(final File file, final String data, final CallBack callBack) {
|
// Observable.create(new ObservableOnSubscribe<Object>() {
|
//
|
// public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
|
// try {
|
// if (!file.exists()) {
|
// if (!file.createNewFile()) {
|
// emitter.onError(new Throwable("文件创建失败"));
|
// }
|
// }
|
// FileOutputStream fileOutputStream = new FileOutputStream(file);
|
// fileOutputStream.write(data.getBytes());
|
// emitter.onNext("ok");
|
// fileOutputStream.flush();
|
// fileOutputStream.close();
|
// emitter.onComplete();
|
// } catch (FileNotFoundException e) {
|
// emitter.onError(e);
|
// e.printStackTrace();
|
// } catch (IOException e) {
|
// emitter.onError(e);
|
// e.printStackTrace();
|
// }
|
// }
|
// }).subscribeOn(Schedulers.io())
|
// .observeOn(AndroidSchedulers.mainThread())
|
// .subscribe(new Observer<Object>() {
|
// private Disposable disposable;
|
//
|
//
|
// public void onSubscribe(Disposable d) {
|
// disposable = d;
|
// }
|
//
|
//
|
// public void onNext(Object o) {
|
// callBack.onSuccess(o.toString());
|
// dispose(disposable);
|
// }
|
//
|
//
|
// public void onError(Throwable e) {
|
// callBack.onFailure(e.getMessage());
|
// dispose(disposable);
|
// }
|
//
|
//
|
// public void onComplete() {
|
// dispose(disposable);
|
// }
|
// });
|
//
|
//
|
// }
|
//
|
// public static void readFile(final File file, final CallBack callBack) {
|
// Observable.create(new ObservableOnSubscribe<Object>() {
|
//
|
// public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
|
// try {
|
// FileReader fileReader = new FileReader(file);
|
// StringBuilder stringBuilder = new StringBuilder();
|
// char[] chars = new char[100];
|
// int length;
|
// while ((length = fileReader.read(chars)) != -1) {
|
// stringBuilder.append(chars, 0, length);
|
// }
|
//// System.out.println(stringBuilder.toString());
|
// fileReader.close();
|
// emitter.onNext(stringBuilder.toString());
|
// emitter.onComplete();
|
// } catch (FileNotFoundException e) {
|
// emitter.onError(e);
|
// e.printStackTrace();
|
// } catch (IOException e) {
|
// emitter.onError(e);
|
// e.printStackTrace();
|
// }
|
// }
|
// }).subscribeOn(Schedulers.io())
|
// .observeOn(AndroidSchedulers.mainThread())
|
// .subscribe(new Observer<Object>() {
|
// private Disposable disposable;
|
//
|
//
|
// public void onSubscribe(Disposable d) {
|
// disposable = d;
|
// }
|
//
|
//
|
// public void onNext(Object o) {
|
// callBack.onSuccess(o.toString());
|
// dispose(disposable);
|
// }
|
//
|
//
|
// public void onError(Throwable e) {
|
// callBack.onFailure(e.getMessage());
|
// dispose(disposable);
|
// }
|
//
|
//
|
// public void onComplete() {
|
// dispose(disposable);
|
// }
|
// });
|
//
|
//
|
// }
|
//
|
// private static void dispose(Disposable disposable) {
|
// if (disposable != null && !disposable.isDisposed()) {
|
// disposable.dispose();
|
// }
|
// }
|
public static String getPath(final Uri uri) {
|
// DocumentProvider
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(BaseApplication.getApplication(), 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];
|
}
|
}
|
// DownloadsProvider
|
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);
|
final String[] split = id.split(":");
|
return split[1];
|
}
|
// 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 getDataColumn2(contentUri, selection, selectionArgs);
|
}
|
}
|
// MediaStore (and general)
|
else if ("content".equalsIgnoreCase(uri.getScheme())) {
|
return getDataColumn2(uri, null, null);
|
}
|
// File
|
else if ("file".equalsIgnoreCase(uri.getScheme())) {
|
return uri.getPath();
|
}
|
return null;
|
}
|
|
public static String getRealPathFromURI(Uri contentUri) {
|
String res = null;
|
String[] proj = {MediaStore.Images.Media.DATA};
|
Cursor cursor = BaseApplication.getApplication().getContentResolver().query(contentUri, proj, null, null, null);
|
if (null != cursor && cursor.moveToFirst()) {
|
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
|
res = cursor.getString(column_index);
|
cursor.close();
|
}
|
return res;
|
}
|
|
/**
|
* Get the value of the data column for this Uri. This is useful for
|
* MediaStore Uris, and other file-based ContentProviders.
|
*
|
* @param uri The Uri to query.
|
* @param selection (Optional) Filter used in the query.
|
* @param selectionArgs (Optional) Selection arguments used in the query.
|
* @return The value of the _data column, which is typically a file path.
|
*/
|
public static String getDataColumn2(Uri uri, String selection,
|
String[] selectionArgs) {
|
Cursor cursor = null;
|
final String column = "_data";
|
final String[] projection = {column};
|
try {
|
cursor = BaseApplication.getApplication().getContentResolver()
|
.query(uri, projection, selection, selectionArgs, null);
|
if (cursor != null && cursor.moveToFirst()) {
|
final int column_index = cursor.getColumnIndexOrThrow(column);
|
return cursor.getString(column_index);
|
}
|
} finally {
|
if (cursor != null)
|
cursor.close();
|
}
|
return null;
|
}
|
|
/**
|
* @param uri The Uri to check.
|
* @return Whether the Uri authority is ExternalStorageProvider.
|
*/
|
public static boolean isExternalStorageDocument(Uri uri) {
|
return "com.android.externalstorage.documents".equals(uri.getAuthority());
|
}
|
|
/**
|
* @param uri The Uri to check.
|
* @return Whether the Uri authority is DownloadsProvider.
|
*/
|
public static boolean isDownloadsDocument(Uri uri) {
|
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
|
}
|
|
/**
|
* @param uri The Uri to check.
|
* @return Whether the Uri authority is MediaProvider.
|
*/
|
public static boolean isMediaDocument(Uri uri) {
|
return "com.android.providers.media.documents".equals(uri.getAuthority());
|
}
|
|
/**
|
* 解决小米手机上获取图片路径为null的情况
|
*
|
* @param intent
|
* @return
|
*/
|
public Uri getImageUri(Context context, android.content.Intent intent) {
|
Uri uri = intent.getData();
|
String type = intent.getType();
|
if (uri.getScheme().equals("file") && (type.contains("image/"))) {
|
String path = uri.getEncodedPath();
|
if (path != null) {
|
path = Uri.decode(path);
|
ContentResolver cr = context.getContentResolver();
|
StringBuffer buff = new StringBuffer();
|
buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
|
.append("'" + path + "'").append(")");
|
Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
|
new String[]{MediaStore.Images.ImageColumns._ID},
|
buff.toString(), null, null);
|
int index = 0;
|
for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
|
index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);
|
// set _id value
|
index = cur.getInt(index);
|
}
|
if (index == 0) {
|
// do nothing
|
} else {
|
Uri uri_temp = Uri
|
.parse("content://media/external/images/media/"
|
+ index);
|
if (uri_temp != null) {
|
uri = uri_temp;
|
}
|
}
|
}
|
}
|
return uri;
|
}
|
}
|