[英]Get file from res/raw folder
I need help with File. 我需要有关文件的帮助。
int aIdSound=R.raw.sound;
String path=getString(aIdSound); // return res/raw/sound.wav
File file=new File(path);
if(file.exists()){
// File doesnt exist.
}
So I have tried 所以我尝试了
InputStream input=getResources().openRawResource(aIdSound);
But I need File class, so is there any way how to change InputStream to File or any idea how to getFile by id? 但是我需要File类,所以有什么办法如何将InputStream更改为File或任何想法如何通过id获取File?
You have to read InputStream
, write it to an external file with FileOutputStream
to get a File
instance of your raw resource. 您必须阅读InputStream
,然后使用FileOutputStream
将其写入外部文件以获取原始资源的File
实例。
Or I missed an API. 或者我错过了API。 :) :)
Try using this: 尝试使用此:
final int resId = getResources().getIdentifier("fileName.wav", "raw", getPackageName());
If you are trying to play audio, you might want to investigate into MediaPlayer. 如果您尝试播放音频,则可能需要调查MediaPlayer。 Here is how I used it: 这是我的用法:
try {
final MediaPlayer player = MediaPlayer.create(this, redId);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If you decide you want to use an externally saved file then you should use: 如果您决定要使用外部保存的文件,则应使用:
File fis = new File(Environment.getExternalStorageDirectory().getPath() + "fileName" + ".wav");
Uri external = Uri.fromFile(fis);
final MediaPlayer player = MediaPlayer.create(this, external);
Place that file in Asserts
Folder 将该文件放置在Asserts
文件夹中
you can get that file using 你可以使用该文件
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
// reading a assert file context.getAssets().open("filename.xml")
Document doc = docBuilder.parse(context.getAssets().open("filename.xml"));
or from External Folder (SD card) 或从外部文件夹(SD卡)
try{
// Creating Input Stream
File file = new File(context.getExternalFilesDir(null), filename);
FileInputStream myInput = new FileInputStream(file);
}catch (Exception e){
e.printStackTrace();
Toast.makeText(context, "Error in reading the file", Toast.LENGTH_SHORT).show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.