下面列出了怎么用android.content.res.AssetManager的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pubu_layout);
puBuLayout = (PuBuLayout) findViewById(R.id.pubu_layout);
//获取AssetManager
AssetManager manager = getAssets();
try {
//获取Assets目录中的文件,得到文件名数组
String[] images = manager.list("images");
for(int i=0; i<images.length;i++){
//向布局中添加Bitmap
//把文件转换Bitmap
InputStream in = manager.open("images/" + images[i]);
Bitmap bitmap = BitmapFactory.decodeStream(in);
puBuLayout.addImage(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void loadModel(String path) throws IOException {
mInputStream = mContext.getAssets().open(path + "/W", AssetManager.ACCESS_BUFFER);
ByteBuffer bb = readInput(mInputStream);
FloatBuffer.wrap(W).put(bb.asFloatBuffer());
// padding for GPU BLAS when necessary.
int W_height_input = in_channels * ksize * ksize;
if (padded_Y_blas == W_height_input) {
// If the input width already satisfies the requirement, just copy to the Allocation.
W_alloc.copyFrom(W);
} else {
// If not, a temp allocation needs to be created.
Allocation input = Allocation.createTyped(mRS,
Type.createXY(mRS, Element.F32(mRS), W_height_input, out_channels));
input.copyFrom(W);
W_alloc.copy2DRangeFrom(0, 0, W_height_input, out_channels, input, 0, 0);
}
mInputStream = mContext.getAssets().open(path + "/b", AssetManager.ACCESS_BUFFER);
bb = readInput(mInputStream);
FloatBuffer.wrap(b).put(bb.asFloatBuffer());
b_alloc.copyFrom(b);
mInputStream.close();
Log.v(TAG, "Convolution2D loaded: " + b[0]);
}
/**
* @brief assets路径内内容复制进目录路径
* @param assetsPath assets路径
* @param dirPath 目录路径
* @param isSmart true: only when a file doesn't exist; false: override.
* @throws IOException
*/
public void assetsCopy(String assetsPath, String dirPath, boolean isSmart) throws IOException {
AssetManager am = mContext.getAssets();
String[] list = am.list(assetsPath);
if (list.length == 0) { // 文件
File file = new File(dirPath);
if (!isSmart || !file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
InputStream in = am.open(assetsPath);
FileOutputStream fout = new FileOutputStream(file);
write(in, fout); // 复制
}
} else { // 目录
for (String path : list) {
assetsCopy(join(assetsPath, path), join(dirPath, path), isSmart);
}
}
}
private static String loadJSONFromAsset(Context context, String jsonFileName) {
String json = null;
InputStream is = null;
try {
AssetManager manager = context.getAssets();
Log.d(TAG,"path "+jsonFileName);
is = manager.open(jsonFileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
public static void findAPKFile(String filepath, Context context) {
String apkFilepath = getAPKFilepath(context);
// Get the offset and length for the file: theUrl, that is in your
// assets folder
AssetManager assetManager = context.getAssets();
try {
AssetFileDescriptor assFD = assetManager.openFd(filepath);
if (assFD != null) {
long offset = assFD.getStartOffset();
long fileSize = assFD.getLength();
assFD.close();
// **** offset and fileSize are the offset and size
// **** in bytes of the asset inside the APK
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* V2 - Helper function to copy multiple files from asset to SDCard
*/
public void copyFileOrDir(String fullPath, String path) {
AssetManager assetManager = context.getAssets();
String assets[];
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(fullPath, path);
} else {
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
for (String asset : assets) {
copyFileOrDir(fullPath, path + "/" + asset);
}
}
} catch (IOException ex) {
Log.e("Sample Data", "I/O Exception", ex);
}
}
public static AssetFileDescriptor getAssetFileDescriptor(String assetName) {
Context context = CoreMaterialApplication.getContext();
if (context == null) {
return null;
}
AssetManager assets = context.getAssets();
if (assets == null) {
return null;
}
try {
return assets.openFd(assetName);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Create new android project
*
* @param context - android context to get assets template
* @param dir - The directory will contain the project
* @param projectName - Name of project, it will be used for create root directory
* @param useCompatLibrary - <code>true</code> if need copy android compat library
*/
@Override
public AndroidAppProject createNewProject(Context context, File dir, String projectName,
String packageName, String activityName, String mainLayoutName,
String appName, boolean useCompatLibrary) throws Exception {
String activityClass = String.format("%s.%s", packageName, activityName);
File projectDir = new File(dir, projectName);
AndroidAppProject project = new AndroidAppProject(projectDir, activityClass, packageName);
//create directory
project.mkdirs();
AssetManager assets = context.getAssets();
createGradleFile(project);
createRes(project, useCompatLibrary, appName);
createManifest(project, activityClass, packageName, assets);
createMainActivity(project, activityClass, packageName, activityName, appName, useCompatLibrary, assets);
createMainLayoutXml(project, mainLayoutName);
copyLibrary(project, useCompatLibrary);
return project;
}
private static void listFontFiles(AssetManager assets, Collection<String> fonts, String path) {
try {
String[] list = assets.list(path);
if (list.length > 0) {
// it's a folder
for (String file : list) {
String prefix = "".equals(path) ? "" : path + File.separator;
listFontFiles(assets, fonts, prefix + file);
}
} else if (path.endsWith("ttf")) {
// it's a font file
fonts.add(path);
}
} catch (IOException ignore) {
}
}
public List<String>readingList()
{
AssetManager am = MainActivity.mainActivity.getAssets();
String dir = "oc-reading";
dir = OBUtils.stringByAppendingPathComponent(dir,"books");
try
{
if (OBUtils.assetsDirectoryExists(dir))
{
String files[] = am.list(dir);
return Arrays.asList(files);
}
}
catch (IOException e)
{
}
return Collections.emptyList();
}
public static ArrayList<Bank> loadHotBank(AssetManager assetManager) {
ArrayList<Bank> hotBanks = null;
try {
InputStream is = assetManager.open("bank/hot_bank.json");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int offset;
while( (offset = is.read(buffer)) != -1 ) {
baos.write(buffer, 0, offset);
}
is.close();
baos.flush();
hotBanks = new Gson().fromJson(baos.toString(), new TypeToken<ArrayList<Bank>>(){}.getType());
is.close();
baos.close();
} catch (IOException e) {
}
return hotBanks == null ? new ArrayList<Bank>() : hotBanks;
}
public
@Nullable Typeface getTypeface(
String fontFamilyName,
int style,
AssetManager assetManager) {
FontFamily fontFamily = mFontCache.get(fontFamilyName);
if (fontFamily == null) {
fontFamily = new FontFamily();
mFontCache.put(fontFamilyName, fontFamily);
}
Typeface typeface = fontFamily.getTypeface(style);
if (typeface == null) {
typeface = createTypeface(fontFamilyName, style, assetManager);
if (typeface != null) {
fontFamily.setTypeface(style, typeface);
}
}
return typeface;
}
/**
* Loads all files from a given assets directory (in alphabetical order) as consecutive tiles of an {@link TiledTextureRegion}.
*
* @param pBuildableBitmapTextureAtlas
* @param pAssetManager
* @param pAssetSubdirectory to load all files from "gfx/flowers" put "flowers" here (assuming, that you've used {@link BitmapTextureAtlasTextureRegionFactory#setAssetBasePath(String)} with "gfx/" before.)
* @return
*/
public static TiledTextureRegion createTiledFromAssetDirectory(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final AssetManager pAssetManager, final String pAssetSubdirectory) {
final String[] files;
try {
files = pAssetManager.list(BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetSubdirectory);
} catch (final IOException e) {
throw new AndEngineRuntimeException("Listing assets subdirectory: '" + BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetSubdirectory + "' failed. Does it exist?", e);
}
final int fileCount = files.length;
final TextureRegion[] textures = new TextureRegion[fileCount];
for (int i = 0; i < fileCount; i++) {
final String assetPath = pAssetSubdirectory + "/" + files[i];
textures[i] = BitmapTextureAtlasTextureRegionFactory.createFromAsset(pBuildableBitmapTextureAtlas, pAssetManager, assetPath);
}
return new TiledTextureRegion(pBuildableBitmapTextureAtlas, textures);
}
private void initEMJCategories() {
AssetManager assetManager = BaseApplication.getInstance().getBaseContext().getResources().getAssets();
try {
String[] files = assetManager.list(EMOJI_PATH);
StickerCategory category;
for (String name : files) {
if (!FileUtil.hasExtentsion(name)) {
if (null == stickerOrder.get(name)) continue;
int posi = stickerOrder.get(name);
boolean bigStick = bigStickers.contains(name);
category = new StickerCategory(name, posi, bigStick);
stickerCategories.add(category);
}
}
Collections.sort(stickerCategories, new Comparator<StickerCategory>() {
@Override
public int compare(StickerCategory lhs, StickerCategory rhs) {
return lhs.getOrder() - rhs.getOrder();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
@NonNull
@Override
protected Boolean doInBackground(Void... voids) {
SplashActivity activity = activityReference.get();
StorageUtils.makeIslamicLibraryShamelaDirectory(activity);
if (activity != null) {
AssetManager assetManager = activity.getAssets();
InputStream in;
try {
in = assetManager.open(DownloadFileConstants.COMPRESSED_ONLINE_DATABASE_NAME);
if (!UnZipIntentService.unzip(in,
StorageUtils.getIslamicLibraryShamelaBooksDir(activity),
this::publishProgress)) {
throw new IOException("unzip failed for main database");
}
} catch (IOException e) {
Timber.e(e);
return false;
}
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ghost);
AssetManager assetManager = getAssets();
try {
InputStream inputStream = assetManager.open("words.txt");
//dictionary = new SimpleDictionary(inputStream);
dictionary = new FastDictionary(inputStream);
} catch (IOException e) {
Toast toast = Toast.makeText(this, "Could not load dictionary", Toast.LENGTH_LONG);
toast.show();
}
if (savedInstanceState == null) {
onStart(null);
} else {
userTurn = savedInstanceState.getBoolean(KEY_USER_TURN);
currentWord = savedInstanceState.getString(KEY_CURRENT_WORD);
String status = savedInstanceState.getString(KEY_SAVED_STATUS);
((TextView) findViewById(R.id.ghostText)).setText(currentWord);
((TextView) findViewById(R.id.gameStatus)).setText(status);
}
}
private static String loadJSONFromAsset(Context context, String jsonFileName) {
String json = null;
InputStream is = null;
try {
AssetManager manager = context.getAssets();
Log.d(TAG, "path " + jsonFileName);
is = manager.open(jsonFileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
static void install(String externalResourceFile) {
try {
AssetManager newAssetManager = createAssetManager(externalResourceFile);
// Find the singleton instance of ResourcesManager
Class<?> clazz = Class.forName("android.app.ActivityThread");
Method mGetInstance = clazz.getDeclaredMethod("currentActivityThread");
mGetInstance.setAccessible(true);
Object resourcesManager = mGetInstance.invoke(null);
// Iterate over all known Resources objects
Field fMActiveResources = clazz.getDeclaredField("mActiveResources");
fMActiveResources.setAccessible(true);
@SuppressWarnings("unchecked")
Map<?, WeakReference<Resources>> arrayMap =
(Map<?, WeakReference<Resources>>) fMActiveResources.get(resourcesManager);
setAssetManager(arrayMap, newAssetManager);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public BitmapFontPage(final AssetManager pAssetManager, final String pAssetBasePath, final String pData) throws IOException {
final String[] pageAttributes = TextUtils.SPLITPATTERN_SPACE.split(pData, BitmapFont.TAG_PAGE_ATTRIBUTECOUNT + 1);
if ((pageAttributes.length - 1) != BitmapFont.TAG_PAGE_ATTRIBUTECOUNT) {
throw new FontException("Expected: '" + BitmapFont.TAG_PAGE_ATTRIBUTECOUNT + "' " + BitmapFont.TAG_PAGE + " attributes, found: '" + (pageAttributes.length - 1) + "'.");
}
if (!pageAttributes[0].equals(BitmapFont.TAG_PAGE)) {
throw new FontException("Expected: '" + BitmapFont.TAG_PAGE + "' attributes.");
}
this.mID = BitmapFont.getIntAttribute(pageAttributes, BitmapFont.TAG_PAGE_ATTRIBUTE_ID_INDEX, BitmapFont.TAG_PAGE_ATTRIBUTE_ID);
final String file = BitmapFont.getStringAttribute(pageAttributes, BitmapFont.TAG_PAGE_ATTRIBUTE_FILE_INDEX, BitmapFont.TAG_PAGE_ATTRIBUTE_FILE);
final String assetPath = pAssetBasePath + file;
this.mTexture = new BitmapTexture(BitmapFont.this.mTextureManager, new AssetInputStreamOpener(pAssetManager, assetPath), BitmapFont.this.mBitmapTextureFormat, BitmapFont.this.mTextureOptions);
}
/**
* Produce a welcome screen
*
* @return text to dump on the screen on session startup
*/
private String getWelcomeScreen() {
try {
RemoteKeyboardService myService = RemoteKeyboardService.self;
AssetManager assetManager = myService.getResources().getAssets();
InputStream inputStream = assetManager.open("welcomescreen.txt");
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
return s.next();
}
catch (Exception exp) {
Log.w(TAG, exp);
}
return "";
}
public static List<String> readLabels(Context context, String labelsFile) {
AssetManager assetManager = context.getAssets();
ArrayList<String> result = new ArrayList<>();
try (InputStream is = assetManager.open(labelsFile);
BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
String line;
while ((line = br.readLine()) != null) {
result.add(line);
}
return result;
} catch (IOException ex) {
throw new IllegalStateException("Cannot read labels from " + labelsFile);
}
}
public static int setDefaultGameData(Context context, KcaDBHelper helper) {
boolean valid_data = false;
String current_version = getStringPreferences(context, PREF_KCA_DATA_VERSION);
String default_version = context.getString(R.string.default_gamedata_version);
if (helper.getJsonObjectValue(DB_KEY_STARTDATA) != null && KcaUtils.compareVersion(current_version, default_version)) {
if (KcaApiData.isGameDataLoaded()) return 1;
JsonObject start_data = helper.getJsonObjectValue(DB_KEY_STARTDATA);
if (start_data.has("api_data") && start_data.get("api_data").isJsonObject()) {
KcaApiData.getKcGameData(start_data.getAsJsonObject("api_data"));
valid_data = true;
}
}
if (!valid_data) {
try {
AssetManager assetManager = context.getAssets();
AssetManager.AssetInputStream ais =
(AssetManager.AssetInputStream) assetManager.open("api_start2");
byte[] bytes = KcaUtils.gzipdecompress(ByteStreams.toByteArray(ais));
helper.putValue(DB_KEY_STARTDATA, new String(bytes));
JsonElement data = new JsonParser().parse(new String(bytes));
JsonObject api_data = new Gson().fromJson(data, JsonObject.class).getAsJsonObject("api_data");
KcaApiData.getKcGameData(api_data);
setPreferences(context, PREF_KCA_VERSION, default_version);
setPreferences(context, PREF_KCA_DATA_VERSION, default_version);
} catch (Exception e) {
return 0;
}
return 1;
} else {
return 1;
}
}
/**
*
* @param drawables
*/
private void addDefaultImages(List<Drawable> drawables) {
// Note: Images are stored as assets instead of as resources
// This because content should be in its raw format as opposed to UI elements
// and to have more control over the decoding of image files
AssetManager assets = getAssets();
Resources resources = getResources();
try {
List<String> images = Arrays.asList(assets.list(DEFAULT_IMAGES_FOLDER));
Collections.sort(images);
for(String image: images) {
InputStream is = null;
try {
is = assets.open(DEFAULT_IMAGES_FOLDER + "/" + image);
Bitmap bitmap = BitmapFactory.decodeStream(is, null, BITMAP_FACTORY_OPTIONS);
drawables.add(new BitmapDrawable(resources, bitmap));
} finally {
if(is != null) {
try {
is.close();
} catch(IOException ignored) {
}
}
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
public static String loadJSONFromAsset(Context context, String jsonFileName)
throws IOException {
AssetManager manager = context.getAssets();
InputStream is = manager.open(jsonFileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
}
private String[] findPlugin() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list(PLUGIN_NAME);
} catch (IOException e) {
PaLog.e(TAG, e.getMessage());
}
return files;
}
private WebResourceResponse getInjectedKcaCdaJs() {
try {
AssetManager as = context.getAssets();
InputStream is = as.open("kcs_cda.js");
return new WebResourceResponse("application/x-javascript", "utf-8", is);
} catch (IOException e) {
return null;
}
}
private boolean assetExists(String fileName) {
// test using AssetManager.open();
// AssetManager.list() is unreliable eg. on my Android 7 Moto G
// and also reported to be pretty slow.
boolean exists = false;
try {
AssetManager assetManager = getResources().getAssets();
InputStream is = assetManager.open(fileName);
exists = true;
is.close();
} catch(Exception e) {
;
}
return exists;
}
public static Classifier create(AssetManager assetManager, String modelFilename, String labelFilename, int inputSize, boolean isQuantized) throws IOException {
TFLiteObjectDetectionAPIModel d = new TFLiteObjectDetectionAPIModel();
BufferedReader br = new BufferedReader(new InputStreamReader(assetManager.open(labelFilename.split("file:///android_asset/")[1])));
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
d.labels.add(line);
}
br.close();
d.inputSize = inputSize;
try {
int numBytesPerChannel;
d.tfLite = new Interpreter(loadModelFile(assetManager, modelFilename));
d.isModelQuantized = isQuantized;
if (isQuantized) {
numBytesPerChannel = 1;
} else {
numBytesPerChannel = 4;
}
d.imgData = ByteBuffer.allocateDirect((((d.inputSize * 1) * d.inputSize) * 3) * numBytesPerChannel);
d.imgData.order(ByteOrder.nativeOrder());
d.intValues = new int[(d.inputSize * d.inputSize)];
d.tfLite.setNumThreads(6);
d.outputLocations = (float[][][]) Array.newInstance(Float.TYPE, new int[]{1, 2, 4});
d.outputClasses = (float[][]) Array.newInstance(Float.TYPE, new int[]{1, 2});
d.outputScores = (float[][]) Array.newInstance(Float.TYPE, new int[]{1, 2});
d.numDetections = new float[1];
return d;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取所有文件
*
* @param path
* @return
*/
public static String[] getfilesFromAssets(Context context, String path) {
AssetManager assetManager = context.getAssets();
String[] files = null;
try {
files = assetManager.list(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (String str : files) {
System.out.print(str);
}
return files;
}
public SmoothieApplicationModule(Application application, String preferencesName) {
bind(Application.class).toInstance(application);
bind(AccountManager.class).toProviderInstance(new AccountManagerProvider(application));
bind(AssetManager.class).toProviderInstance(new AssetManagerProvider(application));
bind(ContentResolver.class).toProviderInstance(new ContentResolverProvider(application));
bind(Handler.class).toProviderInstance(new HandlerProvider());
bind(PackageManager.class).toProviderInstance(new PackageManagerProvider(application));
bind(Resources.class).toProviderInstance(new ResourcesProvider(application));
bind(SharedPreferences.class)
.toProviderInstance(new SharedPreferencesProvider(application, preferencesName));
bindSystemServices(application);
bindPackageInfo(application);
}