1.直接读取inputstream流
- AssetManager assetManager = getAssets();//獲取其輸入流 然後直接讀取這個流
- InputStream inputStream = assetManager.open("1.txt");
2.複製asset指定文件到制定地方
- /**
- * Copy assets util
- * @param path The dictionary path
- * @param filename The filename
- * @param context Your context
- */
- public void copyAssets(String path, String filename,Context context) {
- try {
- File fpath = new File(PATH);
- if (!fpath.isDirectory()) {
- fpath.mkdirs();
- }
- AssetManager assetManager = context.getAssets();
- InputStream inputStream = assetManager.open(filename);
- FileOutputStream fileOutputStream = new FileOutputStream(PATH
- + filename);
- byte[] buffer = new byte[1024];
- int read;
- while ((read = inputStream.read(buffer)) != -1) {
- fileOutputStream.write(buffer, 0, read);
- }
- inputStream.close();
- inputStream = null;
- fileOutputStream.flush();
- fileOutputStream.close();
- fileOutputStream = null;
- } catch (Exception e) {
- // TODO: handle exception
- }
- }
3.複製assets下所有文件到指定地方
- private static void copyAssets(Context context) {//copy Assets的方法
- AssetManager assetManager = context.getAssets();
- String[] files = null;
- try {
- files = assetManager.list("");
- } catch (IOException e) {
- }
- for (int i = 0; i < files.length; i++) {
- InputStream in = null;
- OutputStream out = null;
- try {
- if (!(new File(Tips.DATA_PATH + files[i])).exists()) {
- in = assetManager.open(files[i]);
- out = new FileOutputStream(Tips.DATA_PATH + files[i]);
- Tips.copyFile(in, out);
- in.close();
- in = null;
- out.flush();
- out.close();
- out = null;
- }
- } catch (Exception e) {
- }
- }
- }
- public static void copyFile(InputStream in, OutputStream out)
- throws IOException {
- byte[] buffer = new byte[1024];//做了个缓冲流
- int read;
- while ((read = in.read(buffer)) != -1) {
- out.write(buffer, 0, read);
- }
- }