Commit fa8b4a52 by wanglei

更新读取Assets文件方法

1 parent c1cc7883
Showing with 43 additions and 8 deletions
...@@ -2,7 +2,7 @@ package com.agenew.mnist; ...@@ -2,7 +2,7 @@ package com.agenew.mnist;
import android.content.Context; import android.content.Context;
import android.content.res.AssetFileDescriptor; import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager; import android.util.Log;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
...@@ -10,16 +10,51 @@ import java.nio.MappedByteBuffer; ...@@ -10,16 +10,51 @@ import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
public class Utils { public class Utils {
private static final String TAG = "Utils";
public static final int PIXEL_SIZE = 28; public static final int PIXEL_SIZE = 28;
private static final String MODEL_FILE = "mnist.tflite"; private static final String MODEL_FILE = "mnist.tflite";
public static MappedByteBuffer loadModelFile(Context context) throws IOException { public static MappedByteBuffer loadModelFile(Context context) throws IOException {
AssetManager assets = context.getAssets(); return loadMappedFile(context, MODEL_FILE);
AssetFileDescriptor fileDescriptor = assets.openFd(MODEL_FILE); }
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = inputStream.getChannel(); public static MappedByteBuffer loadMappedFile(Context context, String filePath) throws IOException {
long startOffset = fileDescriptor.getStartOffset(); AssetFileDescriptor fileDescriptor = context.getAssets().openFd(filePath);
long declaredLength = fileDescriptor.getDeclaredLength(); MappedByteBuffer result = null;
return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength); try {
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
try {
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
result = fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength);
} catch (Throwable e) {
try {
inputStream.close();
} catch (Throwable e1) {
e.addSuppressed(e1);
}
throw e;
} finally {
inputStream.close();
}
} catch (Throwable e) {
if (fileDescriptor != null) {
try {
fileDescriptor.close();
} catch (Throwable e1) {
e.addSuppressed(e1);
}
}
Log.e(TAG, "WL_DEBUG loadMappedFile e = " + e, e);
} finally {
if (fileDescriptor != null) {
fileDescriptor.close();
}
}
return result;
} }
} }
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!