• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package org.tensorflow.lite.task.core;
2 
3 import android.content.Context;
4 import android.content.res.AssetManager;
5 
6 import com.google.common.io.ByteStreams;
7 
8 import java.io.File;
9 import java.io.FileOutputStream;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.nio.ByteBuffer;
13 import java.nio.ByteOrder;
14 
15 /** Helper class for the Java test in Task Libary. */
16 public final class TestUtils {
17 
18     /**
19      * Loads the file and create a {@link File} object by reading a file from the asset directory.
20      * Simulates downloading or reading a file that's not precompiled with the app.
21      *
22      * @return a {@link File} object for the model.
23      */
loadFile(Context context, String fileName)24     public static File loadFile(Context context, String fileName) {
25         File target = new File(context.getFilesDir(), fileName);
26         try (InputStream is = context.getAssets().open(fileName);
27              FileOutputStream os = new FileOutputStream(target)) {
28             ByteStreams.copy(is, os);
29         } catch (IOException e) {
30             throw new AssertionError("Failed to load model file at " + fileName, e);
31         }
32         return target;
33     }
34 
35     /**
36      * Reads a file into a direct {@link ByteBuffer} object from the asset directory.
37      *
38      * @return a {@link ByteBuffer} object for the file.
39      */
loadToDirectByteBuffer(Context context, String fileName)40     public static ByteBuffer loadToDirectByteBuffer(Context context, String fileName)
41             throws IOException {
42         AssetManager assetManager = context.getAssets();
43         InputStream inputStream = assetManager.open(fileName);
44         byte[] bytes = ByteStreams.toByteArray(inputStream);
45 
46         ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.length).order(ByteOrder.nativeOrder());
47         buffer.put(bytes);
48         return buffer;
49     }
50 }