본문 바로가기
모바일개발(Mobile Dev)/IOS개발(ObjectC)

how to use file in android assets

by 테크한스 2017. 9. 2.
반응형


link : https://stackoverflow.com/questions/30888783/key-p12-open-failed-enoent-no-such-file-or-directory


Using AssetManager

        AssetManager am = getAssets();
        InputStream inputStream = am.open("xxxxxxxxxxKey.p12");
        File file = createFileFromInputStream(inputStream);

As a raw resource , put the file in raw folder inside res directory

        InputStream ins = getResources().openRawResource(R.raw.keyfile);
        File file = createFileFromInputStream(ins);

While writing the output file you have to specify where your keyfile actually belongs , in my case I'm using android, I'm creating the file inside the internal storage(emulator/device) inside folder KeyHolder/KeyFile

private File createFileFromInputStream(InputStream inputStream) {

        String path = "";

        File file = new File(Environment.getExternalStorageDirectory(),
                "KeyHolder/KeyFile/");
        if (!file.exists()) {
            if (!file.mkdirs())
                Log.d("KeyHolder", "Folder not created");
            else
                Log.d("KeyHolder", "Folder created");
        } else
            Log.d("KeyHolder", "Folder present");

       path = file.getAbsolutePath();

        try {
            File f = new File(path+"/MyKey");
            OutputStream outputStream = new FileOutputStream(f);
            byte buffer[] = new byte[1024];
            int length = 0;

            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }

            outputStream.close();
            inputStream.close();

            return f;
        } catch (IOException e) {
            // Logging exception
            e.printStackTrace();
        }

        return null;
    }


반응형