我正在尝试获取用户选择的绝对文件路径,“Intent Intent.createChooser”的结果,并在Edittext中将其命名为“editTextPath”,我使用了this method 它的工作正常,但它获取文件路径内部存储的问题与外部SD中的路径相同,关联请参阅此GIF
代码
class MainActivity extends AppCompatActivity {
private Button browse;
private Button read;
private Button clear;
private EditText editTextPath;
private TextView text;
private Intent fileChooserIntent;
private File file;
private Uri selectedFile;
private static final int REQUEST_CODE_DOC = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
browse = (Button) findViewById(R.id.browse);
read = (Button) findViewById(R.id.read);
clear = (Button) findViewById(R.id.clear);
editTextPath = (EditText) findViewById(R.id.editTextPath);
text = (TextView) findViewById(R.id.text);
text.setMovementMethod(new ScrollingMovementMethod());
browse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// fileChooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
// fileChooserIntent.setType("*/*");
// fileChooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
// startActivityForResult(Intent.createChooser(fileChooserIntent, "Select file"), 1);
// setResult(Activity.RESULT_OK);
browseDocuments();
}
});
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TextUtils.isEmpty(editTextPath.getText())) {
editTextPath.setError("The file path cannot be empty");
return;
} else {
isStoragePermissionGranted();
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
text.setText(null);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_DOC && resultCode == Activity.RESULT_OK) {
//String Fpath = data.getData().getPath();
try {
selectedFile = data.getData();
file = new File(getFilePath(MainActivity.this, selectedFile));
editTextPath.setText(file.getAbsolutePath());
String mimeType = getContentResolver().getType(selectedFile);
Log.i("Type of file", mimeType + "");
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.getMessage());
}
}
}
private void readFile() {
try {
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
String line;
while ((line = br.readLine()) != null) {
text.append(line + "\n");
}
br.close();
fileReader.close();
} catch (IOException e) {
Log.e("IOException", e.getMessage());
Log.e("IOException2", e.getCause() + "");
Log.e("IOException3", "exception", e);
Toast.makeText(MainActivity.this, "Cannot read this file", Toast.LENGTH_LONG).show();
}
}
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
readFile();
Log.v("Permission is granted", "Permission is granted");
return true;
} else {
Log.v("Permission is revoked", "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v("", "Permission is granted");
readFile();
return true;
}
}
/*public void enableRuntimePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
Log.e("should request", "should request");
Toast.makeText(this, "I can not read contacts because of permission denied1", Toast.LENGTH_LONG).show();
} else {
Log.e("request permission", "request permission");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
}*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("Read file", "onRequestPermissionsResult");
Toast.makeText(this, "READ_EXTERNAL_STORAGE permission granted", Toast.LENGTH_SHORT).show();
readFile();
}
} else {
Toast.makeText(this, "READ_EXTERNAL_STORAGE permission denied", Toast.LENGTH_SHORT).show();
}
}
@SuppressLint("NewApi")
public static String getFilePath(Context context, Uri uri) throws URISyntaxException {
String selection = null;
String[] selectionArgs = null;
// Uri is different in versions after KITKAT (Android 4.4), we need to
if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
uri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("image".equals(type)) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{
split[1]
};
}
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {
MediaStore.Images.Media.DATA
};
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(uri, projection, selection, selectionArgs, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
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());
}
private void browseDocuments() {
String[] mimeTypes =
{"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
"application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
"application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
"text/plain",
"application/pdf"};
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
setResult(Activity.RESULT_OK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
if (mimeTypes.length > 0) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
} else {
String mimeTypesStr = "";
for (String mimeType : mimeTypes) {
mimeTypesStr += mimeType + "|";
}
intent.setType(mimeTypesStr.substring(0, mimeTypesStr.length() - 1));
}
startActivityForResult(Intent.createChooser(intent, "ChooseFile"), REQUEST_CODE_DOC);
}
}