Android 读取asset文件

读取asset目录下面文件, 返回byte[] , fileName: key/hello.der

public byte[] readStream(String fileName) {
        try{
            InputStream inStream = getResources().getAssets().open(fileName);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while((len = inStream.read(buffer)) != -1){
                outStream.write(buffer, 0, len);
            }
            outStream.close();
            inStream.close();
            return outStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

读取asset目录下面文件, 返回string

public String getFromAssets(String fileName) {
        String content = null; //结果字符串
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open(fileName), "ISO_8859_1" );
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line="";
            StringBuilder builder = new StringBuilder();
            while((line = bufReader.readLine()) != null){
                builder.append(line);
            }
            inputReader.close();
            bufReader.close();
            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

将文件保存到外部

writeFile(key.getBytes(StandardCharsets.ISO_8859_1), "demo/", "hello" + ".der");
    public static boolean writeFile(byte[] buffer, String folder,
                                    String fileName) {
        boolean writeSucc = false;

        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);

        String folderPath = "";
        if (sdCardExist) {
            folderPath = Environment.getExternalStorageDirectory()
                    + File.separator + folder + File.separator;
        } else {
            writeSucc = false;
        }

        File fileDir = new File(folderPath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        File file = new File(folderPath + fileName);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file, true);
            out.write(buffer);
            writeSucc = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return writeSucc;
    }

你可能感兴趣的:(Android 读取asset文件)