Get path of data directory(android)

穿精又带淫゛_ 提交于 2019-12-08 03:12:11

问题


I am using tesseract ocr in my app. In order to use tesseract i need to use several language files that are located at a directory called - 'tessdata'.

This is my method code:

    public String detectText(Bitmap bitmap) {
    TessBaseAPI tessBaseAPI = new TessBaseAPI();
    String DATA_PATH = Environment.getRootDirectory().getPath() + "/tessdata/";

    tessBaseAPI.setDebug(true);
    tessBaseAPI.init(DATA_PATH, "eng"); //Init the Tess with the trained data file, with english language

    tessBaseAPI.setImage(bitmap);

    String text = tessBaseAPI.getUTF8Text();

    tessBaseAPI.end();

    return text;
}

I've used many variations of:

String DATA_PATH = Environment.getRootDirectory().getPath() + "/tessdata/";

and every time the app fails with "path not found" exception. I need a good way to put this directory in the android phone and get the path of it regardless of which phone it is. Right now the 'tessdata' directory can be found at the app root directory.

How can i do that?


回答1:


Don't include "/tessdata/" in your DATA_PATH variable--just leave that part off, but be sure that subfolder exists within the directory specified by DATA_PATH.




回答2:


From sourcecode TessBaseAPI#init

public boolean init(String datapath, String language) {
    ...
    if (!datapath.endsWith(File.separator))
        datapath += File.separator;

    File tessdata = new File(datapath + "tessdata");
    if (!tessdata.exists() || !tessdata.isDirectory())
        throw new IllegalArgumentException("Data path must contain subfolder tessdata!");

That means

  • the tessdata-subdirectory must exist.
  • init gets the parent-folder of "tessdata"

You can create it like this:

File dataPath = Environment.getDataDirectory(); 
   // or any other dir where you app has file write permissions

File tessSubDir = new File(dataPath,"tessdata");

tessSubDir.mkdirs(); // create if it does not exist

tessBaseAPI.init(dataPath.getAbsolutePath(), "eng");


来源:https://stackoverflow.com/questions/32568045/get-path-of-data-directoryandroid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!