我们设置一个按钮,点击即可以弹出应用选择框:
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*"); //这个MIME类型意味着任何类型的文件
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult( Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
}
}
选择了文件,则做出相应操作,这里是将其以byte流形式打印:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECTED:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();// 获取所选择的文件的uri
String path = uri.getPath();//简单处理手段
String str = null;
StringBuffer buff = new StringBuffer();// 可以用StringBuilder代替
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(path)));
while ((str = reader.readLine()) != null)
buff.append(str);
reader.close();
show.setText(buff.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
在从返回的URI中获取路径时,可以更加谨慎,代码如下:
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, projection,null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
参考地址:http://www.jb51.net/article/40697.htm