如何在Android Studio中获取原始资源的文件路径?
我一直在使用教程对图片进行人脸检测。问题是当我获取java上使用的文件路径时如何在Android Studio中获取原始资源的文件路径?,android,file,Android,File,我一直在使用教程对图片进行人脸检测。问题是当我获取java上使用的文件路径时 String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml"; CascadeClassifier classifier = new CascadeClassifier(xmlFile); 如何在android studio上进行翻译。我尝试将lbpcascade_frontalface.xml放在原始资源上。CascadeClassifier是
String xmlFile = "E:/OpenCV/facedetect/lbpcascade_frontalface.xml";
CascadeClassifier classifier = new CascadeClassifier(xmlFile);
如何在android studio上进行翻译。我尝试将lbpcascade_frontalface.xml放在原始资源上。CascadeClassifier是opencv库提供的一个类。唯一的问题是它们只加载了字符串路径(在xmlfile上)。
这是我的密码
String pathtoRes = getRawPathAtempt2(context);
CascadeClassifier cascadeClassifier = new CascadeClassifier();
cascadeClassifier.load(pathtoRes);
我翻译成这样的方法
public String getRawPathAtempt2(Context context) {
return "android.resource://" + context.getPackageName() + "/raw/" + "lbpcascade_frontalface.xml";
}
我得到opencv的一个片段错误,它告诉我文件为空。这意味着我在方法中使用文件路径时出错了。如何获取原始资源上的文件路径?请帮帮我,我已经被困了好几天了
如何获取原始资源上的文件路径
你不能。没有路可走。它是开发机器上的一个文件。它不是设备上的文件。相反,它是设备上的应用程序APK文件中的一个条目
如果您的库支持InputStream
而不是文件系统路径,请在上下文上getResources().openRawResource()
获取原始资源上的InputStream
Uri video = Uri.parse("android.resource://com.test.test/raw/filename");
使用此选项,您可以访问原始文件夹中的文件,如果要访问资产文件夹中的文件,请使用此URL
file:///android_asset/filename
确保没有将扩展名添加到文件名。例如“/movie”不是“/movie.mp4”
请参阅此链接:
这就是我用@CommonWare Answer解决问题的方法
我正在使用输入流来获取文件
is = context.getResources().openRawResource(R.raw.lbpcascade_frontalface);
所以make文件将被打开,我将指出file类
File cascadeDir = context.getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");
然后我使用getAbsolutePath搜索路径文件,如下所示
cascadeClassifier.load(mCascadeFile.getAbsolutePath());
看看我的完整代码
try {
is = context.getResources().openRawResource(R.raw.lbpcascade_frontalface);
File cascadeDir = context.getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");
os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
cascadeClassifier.load(mCascadeFile.getAbsolutePath());
} catch (IOException e) {
Log.i(TAG, "face cascade not found");
}
谢谢你,它的作品。我正在使用inputStream来获取我的文件及其工作的位置:D,我很抱歉再次打扰你,但我应该在这里传递正确的代码作为答案,还是我自己保存代码?@Appem:如果你愿意,当然欢迎你回答你自己的问题,包括你如何解决问题的细节。我很高兴听到你的工作!面对同样的问题,请通过此答案的工作代码