File path from sd card

2019-04-16 15:59发布

问题:

I have mp3 files on sd card . how to get the path of file from sd card on selecting the file?

dynamically !...like if user click on file in list view its path get in variable for use.

public class PlayListActivity extends ListActivity {
    // Songs list
    public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.playlist);    
        ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();    
        SongsManager plm = new SongsManager();
        // get all songs from sdcard
        this.songsList = plm.getPlayList();

        // looping through playlist
        for (int i = 0; i < songsList.size(); i++) {
            // creating new HashMap
            HashMap<String, String> song = songsList.get(i);

            // adding HashList to ArrayList
            songsListData.add(song);
        }    
        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, songsListData,
                R.layout.playlist_item, new String[] { "songTitle" }, new int[] {
                        R.id.songTitle });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();
        // listening to single listitem click
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting listitem index
                int songIndex = position;

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        AndroidBuildingMusicPlayerActivity.class);
                // Sending songIndex to PlayerActivity
                in.putExtra("songIndex", songIndex);
                setResult(100, in);
                // Closing PlayListView
                finish();
            }
        });    
    }
}

回答1:

I think you want to get file from a file open dialog, check out the below link

Reference: Choose File Dialog

You can get path of SD card with the help of command below:

String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.mp3";

So path will be

String path  = baseDir + "/your folder(s)/" + fileName;

Reference is: Android how to use Environment.getExternalStorageDirectory()

Or you can try:

new File("/mnt/external_sd/your folder(s)../file.mp3");//get a file from SD card

Reference: How can I get external SD card path for Android 4.0+?



回答2:

You can use getExternalStorageDirectory() to get the root of the sd card as a File object



回答3:

To get the file you should use something like this

public static byte[] readFile (String file, Context c) throws IOException {
    File f = new
    File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), file);
    if (f.exists())
        return readFile(f);
    else return new byte[0];
}

Then you can decode the file with the byte you got.



回答4:

i think this code will work with you ... try it and follow me with results

public class SongsManager {

final String MEDIA_PATH = new String("/sdcard/");
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();

// Constructor
public SongsManager(){

}

/**d
 * Function to read all mp3 files from sdcard
 * and store the details in ArrayList
 * */
public ArrayList<HashMap<String, String>> getPlayList(){
        File List[] = Environment.getExternalStorageDirectory().listFiles();  

    File home;

    int index=0;

        while(index<List.length)
        {
            home = new File(List[index].getAbsolutePath().toString());
            if (home.listFiles(new FileExtensionFilter()).length > 0) {
            for (File file : home.listFiles(new FileExtensionFilter())) {

                HashMap<String, String> song = new HashMap<String, String>();
                song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4)));
                song.put("songPath", file.getPath());

                // Adding each song to SongList
                songsList.add(song);
            }
            index++;
        }
    }
    // return songs list array
    return songsList;
}



/**
 * Class to filter files which are having .mp3 extension
 * */
class FileExtensionFilter implements FilenameFilter {
    public boolean accept(File dir, String name) {
        return (name.endsWith(".mp3") || name.endsWith(".MP3"));
    }
}

}



回答5:

I have got solution on this after 4 days. Please note following points while giving path to File class in Android(Java):

  1. Use path for internal (call external in android) storage

    String path="/storage/sdcard0/myfile.txt";
    
  2. in memory card

    path="/storage/sdcard1/myfile.txt";
    
  3. mention permissions in Manifest file.

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    
  4. First check file length for confirmation.

  5. Check paths in ES File Explorer regarding sdcard0 & sdcard1 is this same or else...... e.g.

    File file=new File(path);
    long=file.length(); //in Bytes