I am working on an exporting function in an Android application. The files are wav files which are stored in the res/raw folder. How can I access the files?
uri = Uri.parse("android.resource://" + getPackageName() + "/raw/" + selection[i]);
try{
file[i] = new File(uri.getPath());
if(file[i].exists()){
Log.i("EXIST", "EXIST");
}else{
Log.i("EXIST", "NOT");
}
}
catch(Exception e){
Log.i("ERROR", "File Not Found");
}
selection[i] is the filename of the file that I need in the res/raw folder. The code always returns "NOT", which means it has not found the file that I want from the res/raw folder. Can anyone help me please? Thanks.
I'm not sure you can access a resource through a File
like that. Here's how I'm reading HTML files in my raw folder:
public static String getStringFromResource(Context context, @RawRes int id) {
BufferedReader reader = null;
try {
StringBuilder stringBuilder = new StringBuilder();
InputStream inputStream = context.getResources().openRawResource(id);
reader = new BufferedReader(new InputStreamReader(inputStream));
String currentLine;
while ((currentLine = reader.readLine()) != null ) {
stringBuilder.append(currentLine);
}
return stringBuilder.toString();
} catch (IOException e) {
Log.e(TAG, "Error opening raw resource: " + id);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(TAG, "Error closing raw resource: " + id, e);
}
}
}
return null;
}
The key part for you will be the InputStream inputStream = context.getResources().openRawResource(id);
call which gets you a stream to the file. Use that stream to write to the output file you are exporting.
This will return a byte array for your raw file:
Resources res = context.getResources();
InputStream inputStream = res.openRawResource(rawResource);
try {
byte[] b = new byte[inputStream.available()];
inputStream.read(b);
} catch (Exception e) {
// exception thrown
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.