0

Is there a way in Android to access a file simply by its filename and path?

I am trying to move some code into Android from a normal Java project, where I have .wav files stored in a subdirectory of \src (bad practice?). Android cannot access these with the same relative filepath clearly.

Is there a filepath for these files in the Android file system or is it simply not possible to do this?

I've read a few things about the Assets folder so am aware of the fact that you can use this to copy files across into the app location, but it would seem a lot of code to change for what I assumed would not be a big issue.

Thanks in advance for any help.

NIM
  • 111
  • 1
  • 3
  • 2
    I m not sure if the files in \src folder is shipped with apk in the first place.. it has to be asset folder – Shrey Mar 16 '12 at 17:51
  • Have a look at this - it appears to be what you need... http://stackoverflow.com/questions/4210239/how-to-use-relative-path-instead-of-absolute-path – Reinstate Monica Cellio Mar 16 '12 at 17:54
  • I don't think it works even it is compile-able. As asset is the only place where you can keep raw files with folder structure. (Another place would be Res\raw which has no folder structure.) – Calvin Mar 16 '12 at 17:58

2 Answers2

2

If you want to ship your files with your application then there is no other option then placing your files in the assets folder. You can access them by their url:

file:///android_asset/your_file.wav

which is useful in web pages. You can have for instance some CSS stored in assets folder and reference it as follows:

<link rel="stylesheet" type="text/css" href="file:///android_asset/your.css" />

If you want to access files in the Java code, then there are two options.

  • to obtain AssetFileDescriptor by the mentioned url and open InputStream for your file
  • to open InputStream for your file via AssetManager by its file name

No other project folder is packed into the .apk file, except the libs folder which is supposed to distribute libraries, and res folder which is to store resources accesible only via resource methods/loaders. Content files must be in assets folder.

vitakot
  • 3,786
  • 4
  • 27
  • 59
  • OK thanks @vitakot, one quick point though - for the path android_asset, is this always these two words or is there any link to the package or app name in question? e.g. File example = new File("android_asset/example.wav"); – NIM Mar 16 '12 at 18:46
1

for me, I put it in the res/raw folder

MediaPlayer player = new MediaPlayer();
AssetFileDescriptor afd = resources.openRawResourceFd(R.raw.music.wav);
    if (afd != null) {
        player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
                afd.getLength());
        afd.close();
    }
Win Myo Htet
  • 5,377
  • 3
  • 38
  • 56