获取数据目录路径(android)

Get path of data directory(android)

我在我的应用程序中使用 tesseract ocr。为了使用 tesseract,我需要使用位于名为 - 'tessdata'.

的目录中的几个语言文件

这是我的方法代码:

    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;
}

我用过很多变体:

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

并且每次应用程序因 "path not found" 异常而失败。 我需要一种好方法将此目录放在 android phone 中并获取它的路径,而不管它是哪个 phone。现在 'tessdata' 目录可以在应用程序根目录中找到。

我该怎么做?

来自源代码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!");

也就是说

  • tessdata-子目录必须存在。
  • init 获取 "tessdata"
  • 的父文件夹

您可以这样创建它:

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");

不要在您的 DATA_PATH 变量中包含 "/tessdata/"——只保留该部分,但要确保子文件夹存在于 DATA_PATH 指定的目录中。