2014-10-26 12 views
31

Ich möchte den Dateinamen aus SDCAD Dateipfad abrufen. z.B. : /storage/sdcard0/DCIM/Camera/1414240995236.jpg I want get 1414240995236.jpg Ich habe den Code geschrieben, um das gleiche zu holen, aber es funktioniert nicht. Bitte helfen Sie.
Unten ist mein Code:Wie bekomme ich den Dateinamen aus dem Dateipfad in Android

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

    } 

} 

Antwort

106

Ich glaube, Sie Teilzeichenfolge Methode Name der Datei aus dem Pfad String erhalten verwenden können.

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); 
+0

Danke Freund seine Arbeit ... –

+0

funktioniert erfolgreich. –

+8

Ich denke, Sie sollten File.separator anstelle von "/" verwenden –

26

Die einfachste Lösung ist Uri.getLastPathSegment() zu verwenden:

String filename = uri.getLastPathSegment(); 
+0

@manimcaAndroidDeveloper Seien Sie sicher, dass Sie Ihren Dank mit einem upvote zu zeigen, und meine Antwort zu akzeptieren (wenn der Timer läuft aus). –

+0

ya sicher. aber ich kann den Dateinamen nicht bekommen. Ich habe eine Antwort wie folgt erhalten. /storage/sdcard/DCIM/Camera/1414302043784.jpg –

+0

@manimcaAndroidDeveloper Was ist der genaue Code, der das Ergebnis liefert? –

0

können Sie die Common IO Bibliothek benutzen, die Ihnen die Basisnamen der Datei und die Erweiterung bekommen.

String fileUrl=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg"; 
     String fileName=FilenameUtils.getBaseName(fileUrl); 
      String fileExtention=FilenameUtils.getExtension(fileUrl); 
//this will return filename:1414240995236 and fileExtention:jpg 
+0

Leider bekommen viele Leute während der Laufzeit das: "java.lang.NoClassDefFoundError: Fehlgeschlagene Auflösung von: Lorg/apache/commons/io/DateinameUtils; " –

23

Einfache und einfache Möglichkeit, Dateiname

File file = new File("/storage/sdcard0/DCIM/Camera/1414240995236.jpg"); 
String strFileName = file.getName(); 

Nachdem fügen Sie diesen Code und drucken strFileName Sie erhalten strFileName = 1414240995236.jpg

+0

Danke Ravi! – ORY

+0

Sie begrüßen @ORY –

2

Alt Faden zu erhalten, aber dachte, ich würde aktualisieren;

File theFile = ....... 
String theName = theFile.getName(); // Get the file name 
String thePath = theFile.getAbsolutePath(); // Get the full 

Weitere Informationen finden Sie hier; Android File Class

+0

Ich vermisste Rv Panchals Post, upvote ihn. –

3

FilenameUtils zur Rettung:

String filename = FilenameUtils.getName("/storage/sdcard0/DCIM/Camera/1414240995236.jpg"); 
0

Wir Dateinamen unter Code finden:

File file =new File(Path); 
String filename=file.getName(); 
Verwandte Themen