如何从资产中读取多个数据?

时间:2017-09-08 06:18:27

标签: java android ocr tesseract android-assets

您好我正在尝试使用tess-two API制作OCR应用

我需要使用两种经过训练的数据语言

我从资源加载数据,但我不知道如何从中加载多个数据

这是我的代码:

   private void checkFile(File dir) {
    if (!dir.exists()&& dir.mkdirs()){
        copyFiles();
    }
    if(dir.exists()) {
        String datafilepath = datapath+ "/tessdata/eng.traineddata";
        File datafile = new File(datafilepath);

        if (!datafile.exists()) {
            copyFiles();
        }
    }
}

private void copyFiles() {
    try {
        String filepath = datapath + "/tessdata/eng.traineddata";
        AssetManager assetManager = getAssets();

        InputStream instream = assetManager.open("tessdata/eng.traineddata");
        OutputStream outstream = new FileOutputStream(filepath);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = instream.read(buffer)) != -1) {
            outstream.write(buffer, 0, read);
        }


        outstream.flush();
        outstream.close();
        instream.close();

        File file = new File(filepath);
        if (!file.exists()) {
            throw new FileNotFoundException();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

如何更改它以复制多个数据?

1 个答案:

答案 0 :(得分:0)

您应该在后台线程(AsyncTask或线程)中复制大文件,并且可以使用以下逻辑来复制多个训练有素的数据文件:

private void checkFile(File dir) {
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (dir.exists()) {
            copyFiles("/tessdata/eng.traineddata");
            copyFiles("/tessdata/hin.traineddata");
            copyFiles("/tessdata/fra.traineddata");
        }
    }

    private void copyFiles(String path) {
        try {
            String filepath = datapath + path;
            if (!new File(filepath).exists()) {
                AssetManager assetManager = getAssets();

                InputStream instream = assetManager.open(path);
                OutputStream outstream = new FileOutputStream(filepath);

                byte[] buffer = new byte[1024];
                int read;
                while ((read = instream.read(buffer)) != -1) {
                    outstream.write(buffer, 0, read);
                }


                outstream.flush();
                outstream.close();
                instream.close();

                File file = new File(filepath);
                if (!file.exists()) {
                    throw new FileNotFoundException();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }