如何从Android文件路径获取文件名 [英] How to get file name from file path in android
本文介绍了如何从Android文件路径获取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从SD卡的文件路径文件名。
例如: /storage/sdcard0/DCIM/Camera/1414240995236.jpg我想要得到1414240995236.jpg
我已经写了code,以获取相同的,但它不工作。请大家帮帮忙。结果
下面是我的code:
@覆盖
保护无效的onActivityResult(INT申请code,INT结果code,意图数据)
{
如果(要求code == CAPTURE_IMAGE_ACTIVITY_REQUEST_ code){ 如果(结果code == RESULT_OK){ / ***********装入捕捉的图像和数据开始**************** / 字符串imageId = convertImageUriToFile(imageUri,CameraActivity);
//创建并excecute的AsyncTask加载捕获映像 新LoadImagesFromSDCard()执行(+ imageId); / ***********装入捕捉的图像和数据结束**************** /
}否则如果(结果code == RESULT_CANCELED){ Toast.makeText(这一点,照片是没有采取Toast.LENGTH_SHORT).show();
}其他{ Toast.makeText(这一点,照片是没有采取Toast.LENGTH_SHORT).show();
}
}
}
/ ************转换图像URI路径到物理路径************** /公共静态字符串convertImageUriToFile(URI imageUri,活动活动){ 光标光标= NULL;
INT imageID = 0; 尝试{ / ***********的列值想得到******* /
的String [] = PROJ {
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION
}; 光标= activity.managedQuery( imageUri,//获取特定的图像数据URI
PROJ,//哪些列返回
空,// WHERE子句;该行返回(所有行)
空,// WHERE子句选择参数(无)
空//订单by子句(按名称升序) ); //获取查询数据 INT参数:columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
INT columnIndexThumb = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
INT file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // INT orientation_ColumnIndex =光标。
// getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION); INT大小= cursor.getCount(); / *******如果大小为0,则对SD卡没有图像。 ***** / 如果(大小== 0){
imageDetails.setText(无图);
}
其他
{ INT thumbID = 0;
如果(cursor.moveToFirst()){ / ****************捕获的图像细节************ / / *****用于显示在视图中LoadImagesFromSDCard一流的图像****** /
imageID = cursor.getInt(参数:columnIndex); thumbID = cursor.getInt(columnIndexThumb); 字符串路径= cursor.getString(file_ColumnIndex); //字符串方向= cursor.getString(orientation_ColumnIndex); 字符串CapturedImageDetails =CapturedImageDetails:\\ n \\ n
+ImageID:+ imageID +\\ n
+ThumbID:+ thumbID +\\ n
+路径:+路径+\\ n;
full_path_name =路径; //这是我的路
//路径:/storage/sdcard0/DCIM/Camera/1414240995236.jpg我想要得到1414240995236.jpg
//上的活动显示拍摄的图像细节
imageDetails.setText(路径); }
}
} {最后
如果(指针!= NULL){
cursor.close();
}
} //返回捕捉到的图像ImageID(通过这种ImageID图像从SD卡装载) 返回+ imageID;
}
/ **
*异步任务从SD卡中加载图像。
*
* @author Android示例
*
* ///使用类扩展的AsyncTask类公共类LoadImagesFromSDCard扩展的AsyncTask<弦乐,太虚,太虚> { 私人ProgressDialog对话=新ProgressDialog(CameraPhotoCapture.this); 位图mBitmap; 在preExecute保护无效(){
/ ******注意:您可以在这里称之为UI元素。 ***** / //进度对话框
Dialog.setMessage(加载SD卡从形象..);
Dialog.show();
}
//后呼吁preExecute方法
保护无效doInBackground(字符串的URL ...){ 位图位图= NULL;
位图newBitmap = NULL;
URI URI = NULL;
尝试{ / ** Uri.withAppendedPath方法说明
*参数
*开放的基本URI追加路径段
* pathSegment EN codeD路径段追加
*回报
*新的URI的基础上与基本URI附加到路径的给定段
* / URI = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,+网址[0]); / **************德code的输入流中的位图。 ********* /
位= BitmapFactory.de codeStream(getContentResolver()openInputStream(URI)); 如果(位图!= NULL){ / *********创建一个新的位图,从现有的位图进行缩放。 *********** / newBitmap = Bitmap.createScaledBitmap(位图,170,170,TRUE); bitmap.recycle(); 如果(newBitmap!= NULL){ mBitmap = newBitmap;
}
}
}赶上(IOException异常五){
//错误获取图像,尝试恢复 / *********取消对此任务的执行。 ********** /
取消(真);
} 返回null;
}
保护无效onPostExecute(虚空未使用){ //注意:您可以在这里称之为UI元素。 //关闭进度对话框
Dialog.dismiss(); 如果(mBitmap!= NULL)
{
//设置图像到的ImageView showImg.setImageBitmap(mBitmap);
} }}
解决方案
我认为你可以使用子串梅索德从路径字符串获取文件的名称。
字符串PATH =:/存储/ sdcard0 / DCIM /摄像机/ 1414240995236.jpg;用一个临时字符串//它包含你image..im的路径..
字符串文件名= path.substring(path.lastIndexOf(/)+ 1);
I want to get file name from sdcard file path.
e.g. :/storage/sdcard0/DCIM/Camera/1414240995236.jpg I want get 1414240995236.jpg
I have written the code to fetch the same but it is not working. Please help.
Below is my code:
@Override
protected void onActivityResult( int requestCode, int resultCode, Intent data)
{
if ( requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if ( resultCode == RESULT_OK) {
/*********** Load Captured Image And Data Start ****************/
String imageId = convertImageUriToFile( imageUri,CameraActivity);
// Create and excecute AsyncTask to load capture image
new LoadImagesFromSDCard().execute(""+imageId);
/*********** Load Captured Image And Data End ****************/
} else if ( resultCode == RESULT_CANCELED) {
Toast.makeText(this, " Picture was not taken ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, " Picture was not taken ", Toast.LENGTH_SHORT).show();
}
}
}
/************ Convert Image Uri path to physical path **************/
public static String convertImageUriToFile ( Uri imageUri, Activity activity ) {
Cursor cursor = null;
int imageID = 0;
try {
/*********** Which columns values want to get *******/
String [] proj={
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION
};
cursor = activity.managedQuery(
imageUri, // Get data for specific image URI
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null // Order-by clause (ascending by name)
);
// Get Query Data
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int columnIndexThumb = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//int orientation_ColumnIndex = cursor.
// getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
int size = cursor.getCount();
/******* If size is 0, there are no images on the SD Card. *****/
if (size == 0) {
imageDetails.setText("No Image");
}
else
{
int thumbID = 0;
if (cursor.moveToFirst()) {
/**************** Captured image details ************/
/***** Used to show image on view in LoadImagesFromSDCard class ******/
imageID = cursor.getInt(columnIndex);
thumbID = cursor.getInt(columnIndexThumb);
String Path = cursor.getString(file_ColumnIndex);
//String orientation = cursor.getString(orientation_ColumnIndex);
String CapturedImageDetails = " CapturedImageDetails : \n\n"
+" ImageID :"+imageID+"\n"
+" ThumbID :"+thumbID+"\n"
+" Path :"+Path+"\n";
full_path_name=Path;
//this is my path
//Path :/storage/sdcard0/DCIM/Camera/1414240995236.jpg i want get 1414240995236.jpg
// Show Captured Image detail on activity
imageDetails.setText(Path);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
// Return Captured Image ImageID ( By this ImageID Image will load from sdcard )
return ""+imageID;
}
/**
* Async task for loading the images from the SD card.
*
* @author Android Example
*
*/
// Class with extends AsyncTask class
public class LoadImagesFromSDCard extends AsyncTask<String, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(CameraPhotoCapture.this);
Bitmap mBitmap;
protected void onPreExecute() {
/****** NOTE: You can call UI Element here. *****/
// Progress Dialog
Dialog.setMessage(" Loading image from Sdcard..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
try {
/** Uri.withAppendedPath Method Description
* Parameters
* baseUri Uri to append path segment to
* pathSegment encoded path segment to append
* Returns
* a new Uri based on baseUri with the given segment appended to the path
*/
uri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + urls[0]);
/************** Decode an input stream into a bitmap. *********/
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
if (bitmap != null) {
/********* Creates a new bitmap, scaled from an existing bitmap. ***********/
newBitmap = Bitmap.createScaledBitmap(bitmap, 170, 170, true);
bitmap.recycle();
if (newBitmap != null) {
mBitmap = newBitmap;
}
}
} catch (IOException e) {
// Error fetching image, try to recover
/********* Cancel execution of this task. **********/
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if(mBitmap != null)
{
// Set Image to ImageView
showImg.setImageBitmap(mBitmap);
}
}
}
解决方案
i think you can use substring methode to get name of file from the path string.
String path=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg";//it contain your path of image..im using a temp string..
String filename=path.substring(path.lastIndexOf("/")+1);
这篇关于如何从Android文件路径获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文