您的位置:首页 > 移动开发 > Android开发

android中加载assets中的资源文件

2012-06-27 16:49 351 查看
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);  
	        }  
	    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: