android.content.res.AssetManager#open()源码实例Demo

下面列出了android.content.res.AssetManager#open() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: XmlToJson   文件: ExampleInstrumentedTest.java
@Test
public void skipAttributeTest() throws Exception {
    Context context = InstrumentationRegistry.getTargetContext();
    AssetManager assetManager = context.getAssets();
    InputStream inputStream = assetManager.open("common.xml");

    XmlToJson xmlToJson = new XmlToJson.Builder(inputStream, null)
            .skipAttribute("/library/book/id")
            .build();

    inputStream.close();

    JSONObject result = xmlToJson.toJson();
    assertTrue(result.has("library"));
    JSONObject library = result.getJSONObject("library");
    assertTrue(library.has("book"));
    JSONArray books = library.getJSONArray("book");
    int size = books.length();
    assertTrue(size == 2);
    for (int i = 0; i < size; ++i) {
        JSONObject book = books.getJSONObject(i);
        assertFalse(book.has("id"));
    }

}
 
源代码2 项目: jxcore-android-basics   文件: FileManager.java
public static String readFile(String location, String encoding) {
    StringBuilder sb = new StringBuilder();
    try {
        AssetManager asm = AppManager.currentContext.getAssets();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                asm.open(location), encoding));

        String str = br.readLine();
        while (str != null) {
            sb.append(str + "\n");
            str = br.readLine();
        }

        br.close();
    } catch (IOException e) {
        Log.w("jxcore-FileManager", "readfile failed");
        e.printStackTrace();
        return null;
    }

    return sb.toString();
}
 
源代码3 项目: rscnn   文件: LabelUtils.java
public static String[] loadLabels(AssetManager assetManager, String file){
    try {
        String[] labels;
        InputStream labelFile = assetManager.open(file);
        byte[] buffer = new byte[labelFile.available()];
        labelFile.read(buffer);
        labelFile.close();
        String labelString = new String(buffer);
        labels = labelString.split("\n");
        for(int i=0;i<labels.length;i++){
            labels[i] = labels[i].split(",")[0].trim();
        }
        return labels;
    } catch (IOException e) {
        LogUtil.e(TAG, "load label error:" + e.getMessage());
        LogUtil.e(TAG, "use default voc 20 class label");
        e.printStackTrace();
    }
    return null;
}
 
源代码4 项目: kcanotify   文件: KcaUtils.java
public static JsonArray getJsonArrayFromAsset(Context context, String name, KcaDBHelper helper) {
    ContextWrapper cw = new ContextWrapper(context);
    JsonArray data = new JsonArray();
    AssetManager am = cw.getAssets();
    try {
        AssetManager.AssetInputStream ais =
                (AssetManager.AssetInputStream) am.open(name);
        byte[] bytes = ByteStreams.toByteArray(ais);
        data = new JsonParser().parse(new String(bytes)).getAsJsonArray();
        ais.close();
    } catch (IOException e1) {
        e1.printStackTrace();
        if (helper != null) helper.recordErrorLog(ERROR_TYPE_DATALOAD, name, "getJsonArrayFromStorage", "1", getStringFromException(e1));
    }
    return data;
}
 
源代码5 项目: AFBaseLibrary   文件: AFCertificateUtil.java
private static InputStream[] getCertificatesByAssert(Context context, String... certificateNames) {
    if (context == null) {
        Logger.d("context is empty");
        return null;
    }
    if (certificateNames == null) {
        Logger.d("certificate is empty");
        return null;
    }

    AssetManager assets = context.getAssets();
    InputStream[] certificates = new InputStream[certificateNames.length];
    for (int i = 0; i < certificateNames.length; i++) {
        String certificateName = certificateNames[i];
        try {
            certificates[i] = assets.open(certificateName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return certificates;
}
 
private void updateUI() {

		LayoutInflater inflater = getLayoutInflater(mBundle);

		// Header
		String cellText = mMonster.getName();
		String cellImage = "icons_monster/" + mMonster.getFileLocation();

		mMonsterLabelTextView.setText(cellText);
        AssetManager manager = getActivity().getAssets();
        try {
            InputStream open = manager.open(cellImage);
            Bitmap bitmap = BitmapFactory.decodeStream(open);
            // Assign the bitmap to an ImageView in this layout
            mMonsterIconImageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }

		updateWeaknessUI();

	}
 
源代码7 项目: kcanotify   文件: KcaUtils.java
public static JsonObject getJsonObjectFromAsset(Context context, String name, KcaDBHelper helper) {
    ContextWrapper cw = new ContextWrapper(context);
    JsonObject data = null;
    AssetManager am = cw.getAssets();
    try {
        AssetManager.AssetInputStream ais =
                (AssetManager.AssetInputStream) am.open(name);
        byte[] bytes = ByteStreams.toByteArray(ais);
        data = new JsonParser().parse(new String(bytes)).getAsJsonObject();
        ais.close();
    } catch (IOException e1) {
        e1.printStackTrace();
        if (helper != null) helper.recordErrorLog(ERROR_TYPE_DATALOAD, name, "getJsonObjectFromStorage", "1", getStringFromException(e1));
    }
    return data;
}
 
@Test
public void testPersistedCoreSDKInfo() {
  Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
  AssetManager assetManager = context.getAssets();
  InputStream inputStream = null;

  try {
    String packageName = context.getPackageName().replace(".test", "");
    inputStream = assetManager.open(SDK_VERSIONS_FOLDER + File.separator + packageName);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    Assert.assertEquals(reader.readLine().split("/")[1], BuildConfig.VERSION_NAME);
    Assert.assertEquals(reader.readLine(), String.format(SECOND_LINE_FORMAT, BuildConfig.VERSION_CODE));
  } catch (IOException exception) {
    Log.e(LOG_TAG, exception.toString());
    fail(exception.toString());
  } finally {
    FileUtils.closeQuietly(inputStream);
  }
}
 
protected File createTempFileFromAsset(String assetPath) throws IOException {
    InputStream inputStream = null;
    FileOutputStream outStream = null;

    try {
        AssetManager assets = getActivity().getResources().getAssets();
        inputStream = assets.open(assetPath);

        File outputDir = getActivity().getCacheDir(); // context being the Activity pointer
        File outputFile = File.createTempFile("prefix", assetPath, outputDir);
        outStream = new FileOutputStream(outputFile);

        final int bufferSize = 1024 * 2;
        byte[] buffer = new byte[bufferSize];
        int n = 0;
        while ((n = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, n);
        }

        return outputFile;
    } finally {
        Utility.closeQuietly(outStream);
        Utility.closeQuietly(inputStream);
    }
}
 
源代码10 项目: Tutorials   文件: Utils.java
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;
}
 
源代码11 项目: EasyNLU   文件: ReminderNlu.java
private Map<String, Float> loadWeights(AssetManager assets){
    Map<String, Float> weights = Collections.emptyMap();

    try {
        Reader reader = new InputStreamReader(assets.open(WEIGHTS_FILE));
        weights = Weights.fromText(reader);
        reader.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return weights;
}
 
源代码12 项目: AndroidBasicProject   文件: ResourceUtil.java
/**
 * 描述:获取Asset中的图片资源.
 *
 * @param context the context
 * @param fileName the file name
 * @return Drawable 图片
 */
public static Drawable getDrawableFromAsset(Context context,String fileName){
    Drawable drawable = null;
    try {
        AssetManager assetManager = context.getAssets();
        InputStream is = assetManager.open(fileName);
        drawable = Drawable.createFromStream(is, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return drawable;
}
 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_word_selection);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    AssetManager assetManager = getAssets();
    try {
        InputStream inputStream = assetManager.open("words.txt");
        dictionary = new PathDictionary(inputStream);
    } catch (IOException e) {
        Toast toast = Toast.makeText(this, "Could not load dictionary", Toast.LENGTH_LONG);
        toast.show();
    }
}
 
源代码14 项目: secure-quick-reliable-login   文件: Utils.java
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;
    }
}
 
源代码15 项目: android-yolo-v2   文件: ClassAttrProvider.java
private void init(final AssetManager assetManager) {
    try (BufferedReader br = new BufferedReader(new InputStreamReader(assetManager.open(Config.LABEL_FILE)))) {
        String line;
        while ((line = br.readLine()) != null) {
            labels.add(line);
            colors.add(convertClassNameToColor(line));
        }
    } catch (IOException ex) {
        throw new RuntimeException("Problem reading label file!", ex);
    }
}
 
源代码16 项目: NGA-CLIENT-VER-OPEN-SOURCE   文件: StringUtils.java
public static String getStringFromAssets(String path) {
    AssetManager assetManager = ContextUtils.getContext().getAssets();
    try (InputStream is = assetManager.open(path)) {
        int length = is.available();
        byte[] buffer = new byte[length];
        is.read(buffer);
        return new String(buffer, StandardCharsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
源代码17 项目: TikTok   文件: OpenGlUtils.java
public static Bitmap getImageFromAssetsFile(Context context, String fileName){
	Bitmap image = null;
    AssetManager am = context.getResources().getAssets();
    try{  
		InputStream is = am.open(fileName);
		image = BitmapFactory.decodeStream(is);
		is.close();
         	}catch (IOException e){
          e.printStackTrace();  
      }  	  
      return image;  	  
}
 
源代码18 项目: FimiX8-RE   文件: TFLiteObjectDetectionAPIModel.java
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);
    }
}
 
private void updateUI() {
	String cellText = mMonster.getName();
	String cellImage = "icons_monster/" + mMonster.getFileLocation();
	
	mMonsterLabelTextView.setText(cellText);
       AssetManager manager = getActivity().getAssets();
       try {
           InputStream open = manager.open(cellImage);
           Bitmap bitmap = BitmapFactory.decodeStream(open);
           // Assign the bitmap to an ImageView in this layout
           mMonsterIconImageView.setImageBitmap(bitmap);
       } catch (IOException e) {
           e.printStackTrace();
       }
       
	// Draw Drawable
	mCutImageView.setImageResource(R.drawable.cut);
	mImpactImageView.setImageResource(R.drawable.impact);
	mShotImageView.setImageResource(R.drawable.shot);
	mKOImageView.setImageResource(R.drawable.stun);
	mFireImageView.setImageResource(R.drawable.fire);
	mWaterImageView.setImageResource(R.drawable.water);
	mIceImageView.setImageResource(R.drawable.ice);
	mThunderImageView.setImageResource(R.drawable.thunder);
	mDragonImageView.setImageResource(R.drawable.dragon);
	
	ArrayList<MonsterDamage> damages = 
			DataManager.get(getActivity()).queryMonsterDamageArray(mMonster.getId());

	MonsterDamage damage = null;
	String body_part, cut, impact, shot, ko, fire, water, ice, thunder, dragon;
	
	LayoutInflater inflater = getLayoutInflater(mBundle);

	// build each row of both tables per record
	for(int i = 0; i < damages.size(); i++) {
		LinearLayout wdRow = (LinearLayout) inflater.inflate(
				R.layout.fragment_monster_damage_listitem, mWeaponDamageTL, false);
		LinearLayout edRow = (LinearLayout) inflater.inflate(
				R.layout.fragment_monster_damage_listitem, mElementalDamageTL, false);
		  
		damage = damages.get(i);
		
		body_part = checkDamageValue(damage.getBodyPart());
		cut = checkDamageValue("" + damage.getCut());
		impact = checkDamageValue("" + damage.getImpact());
		shot = checkDamageValue("" + damage.getShot());
		ko = checkDamageValue("" + damage.getKo());
		fire = checkDamageValue("" + damage.getFire());
		water = checkDamageValue("" + damage.getWater());
		ice = checkDamageValue("" + damage.getIce());
		thunder = checkDamageValue("" + damage.getThunder());
		dragon = checkDamageValue("" + damage.getDragon());

		// Table 1
		TextView body_part_tv1 = (TextView) wdRow.findViewById(R.id.body_part);
		TextView dummy_tv = (TextView) wdRow.findViewById(R.id.dmg1);
		TextView cut_tv = (TextView) wdRow.findViewById(R.id.dmg2);
		TextView impact_tv = (TextView) wdRow.findViewById(R.id.dmg3);
		TextView shot_tv = (TextView) wdRow.findViewById(R.id.dmg4);
		TextView ko_tv = (TextView) wdRow.findViewById(R.id.dmg5);

		// Table 2
		TextView body_part_tv2 = (TextView) edRow.findViewById(R.id.body_part);
		TextView fire_tv = (TextView) edRow.findViewById(R.id.dmg1);
		TextView water_tv = (TextView) edRow.findViewById(R.id.dmg2);
		TextView ice_tv = (TextView) edRow.findViewById(R.id.dmg3);
		TextView thunder_tv = (TextView) edRow.findViewById(R.id.dmg4);
		TextView dragon_tv = (TextView) edRow.findViewById(R.id.dmg5);
		
		body_part_tv1.setText(body_part);
		body_part_tv2.setText(body_part);
		cut_tv.setText(cut);
		impact_tv.setText(impact);
		shot_tv.setText(shot);
		ko_tv.setText(ko);
		fire_tv.setText(fire);
		water_tv.setText(water);
		ice_tv.setText(ice);
		thunder_tv.setText(thunder);
		dragon_tv.setText(dragon);
		dummy_tv.setText("");

		mWeaponDamageTL.addView(wdRow);
		mElementalDamageTL.addView(edRow);
	}
}
 
源代码20 项目: kcanotify_h5-master   文件: KcaUtils.java
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;
}