下面列出了android.content.Context#getAssets ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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 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;
}
@Test
public void skipTagTest() throws Exception {
Context context = InstrumentationRegistry.getTargetContext();
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open("common.xml");
XmlToJson xmlToJson = new XmlToJson.Builder(inputStream, null)
.skipTag("/library/owner")
.build();
inputStream.close();
JSONObject result = xmlToJson.toJson();
assertTrue(result.has("library"));
JSONObject library = result.getJSONObject("library");
assertTrue(library.has("book"));
assertFalse(library.has("owner"));
}
/**
* 从asset路径下读取对应文件转String输出
* @param mContext
* @return
*/
public static String getJson(Context mContext, String fileName) {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
AssetManager am = mContext.getAssets();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
am.open(fileName)));
String next = "";
while (null != (next = br.readLine())) {
sb.append(next);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
sb.delete(0, sb.length());
}
return sb.toString().trim();
}
@Test
public void contentReplacementTest() throws Exception {
Context context = InstrumentationRegistry.getTargetContext();
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open("common.xml");
XmlToJson xmlToJson = new XmlToJson.Builder(inputStream, null)
.setContentName("/library/book", "contentReplacement")
.build();
inputStream.close();
JSONObject result = xmlToJson.toJson();
JSONObject library = result.getJSONObject("library");
JSONArray books = library.getJSONArray("book");
JSONObject book1 = books.getJSONObject(0);
JSONObject book2 = books.getJSONObject(1);
String content1 = book1.getString("contentReplacement");
String content2 = book2.getString("contentReplacement");
assertTrue(content1.equals("James Bond") || content1.equals("Book for the dummies"));
assertTrue(content2.equals("James Bond") || content2.equals("Book for the dummies"));
}
private static void copyFileOrDir(Context context, String path) {
AssetManager assetManager = context.getAssets();
String assets[];
try {
Log.i("tag", "copyFileOrDir() " + path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(context, path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path=" + fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir " + fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
copyFileOrDir(context, p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
public static @Nullable Bitmap getBitmapFromAsset(@NonNull Context context, String filePath) {
AssetManager assetManager = context.getAssets();
InputStream istr;
Bitmap bitmap = null;
try {
istr = assetManager.open(filePath);
bitmap = BitmapFactory.decodeStream(istr);
} catch (IOException e) {
Log.e(TAG, "getBitmapFromAsset: " + e);
}
return bitmap;
}
InstallTask(final Context context,
final String assetPath,
final File directory,
final Handler handler) {
super(context, handler);
mAssetManager = context.getAssets();
mAssetPath = assetPath;
mDirectory = directory;
}
/**
* 获取某个语种下的 Resources 对象
*/
static Resources getLanguageResources(Context context, Locale locale) {
Configuration config = new Configuration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
config.setLocale(locale);
return context.createConfigurationContext(config).getResources();
} else {
config.locale = locale;
return new Resources(context.getAssets(), context.getResources().getDisplayMetrics(), config);
}
}
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");
}
public static byte[] getAssetContent(Context context, String assetName) {
AssetManager am = context.getAssets();
try {
InputStream is = am.open(assetName);
return readFullInputStreamBytes(is);
} catch (Exception e) {
return null;
}
}
public AndroidFFMPEGLocator(Context context){
CPUArchitecture architecture = getCPUArchitecture();
Log.i(TAG,"Detected Native CPU Architecture: " + architecture.name());
if(!ffmpegIsCorrectlyInstalled()){
String ffmpegFileName = getFFMPEGFileName(architecture);
AssetManager assetManager = context.getAssets();
unpackFFmpeg(assetManager,ffmpegFileName);
}
File ffmpegTargetLocation = AndroidFFMPEGLocator.ffmpegTargetLocation();
Log.i(TAG, "Ffmpeg binary location: " + ffmpegTargetLocation.getAbsolutePath() + " is executable? " + ffmpegTargetLocation.canExecute() + " size: " + ffmpegTargetLocation.length() + " bytes");
}
public static String getRSAEncodedString(Context context, String value) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IOException, BadPaddingException, IllegalBlockSizeException {
/*
Example:
try {
JsonObject data = new JsonObject();
data.addProperty("userid", 20181234);
data.addProperty("data", "416D341GX141JI0318W");
String encoded = KcaUtils.getRSAEncodedString(getApplicationContext(), data.toString());
Log.e("KCA", encoded);
data.remove("data");
encoded = KcaUtils.getRSAEncodedString(getApplicationContext(), data.toString());
Log.e("KCA", data.toString());
Log.e("KCA", encoded);
} catch (Exception e) {
e.printStackTrace();
}
*/
List<String> value_list = new ArrayList<>();
for (int i = 0; i < (int) Math.ceil(value.length() / 96.0); i++) {
value_list.add(value.substring(i*96, Math.min((i+1)*96, value.length()) ));
}
AssetManager am = context.getAssets();
AssetManager.AssetInputStream ais =
(AssetManager.AssetInputStream) am.open("kcaqsync_pubkey.txt");
byte[] bytes = ByteStreams.toByteArray(ais);
String publicKeyContent = new String(bytes)
.replaceAll("\\n", "")
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "").trim();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.decode(publicKeyContent, Base64.DEFAULT));
Key encryptionKey = keyFactory.generatePublic(pubSpec);
Cipher rsa = Cipher.getInstance("RSA/None/PKCS1Padding");
rsa.init(Cipher.ENCRYPT_MODE, encryptionKey);
byte[] data_all = {};
for (String item : value_list) {
byte[] item_byte = rsa.doFinal(item.getBytes("utf-8"));
data_all = addAll(data_all, item_byte);
}
String result = Base64.encodeToString(rsa.doFinal(value.getBytes("utf-8")), Base64.DEFAULT).replace("\n", "");
return result;
}
/**
* 设置字体
* @param context
*/
private void init(Context context){
AssetManager assets = context.getAssets();
Typeface font = Typeface.createFromAsset(assets, "fonts/Lobster-1.4.otf");
setTypeface(font);
}
private OptionsManager(@NonNull Context context) {
manager = context.getAssets();
}
public CordovaResourceApi(Context context) {
this.contentResolver = context.getContentResolver();
this.assetManager = context.getAssets();
}
public CordovaResourceApi(Context context, PluginManager pluginManager) {
this.contentResolver = context.getContentResolver();
this.assetManager = context.getAssets();
this.pluginManager = pluginManager;
}
public static boolean applyFontToTextView(final Context context, final TextView textView, final String filePath) {
if (textView == null || context == null) return false;
final AssetManager assetManager = context.getAssets();
final Typeface typeface = TypefaceUtils.load(assetManager, filePath);
return applyFontToTextView(textView, typeface);
}
public AssetRequestHandler(Context context) {
assetManager = context.getAssets();
}
/**
* In most cases, {@link Context#getAssets()} can be used directly. Modified resources are
* used downstream and are set up on application startup, and this method provides access to
* regular assets before that initialization is complete.
*
* This method should ONLY be used for accessing files within the assets folder.
*
* @return Application assets.
*/
public static AssetManager getApplicationAssets() {
Context context = getApplicationContext();
while (context instanceof ContextWrapper) {
context = ((ContextWrapper) context).getBaseContext();
}
return context.getAssets();
}