Cocos2dx在安卓平台下获取到assets目录下文件的绝对路径

需求:curl需要支持https,需要手动设置ca地址用于验证,对于安卓平台,需要将这个ca证书文件放到本地,然后获取到绝对路径


经过很多的尝试,无论是放在res还是assets下,都没能获取到绝对路径

解决方案:虽然不能获取绝对路径,但是能读取到内容,就创建一个新的文件并拷贝内容,然后使用新建的文件路径

     /**
	 * android 获取uri的正确文件路径的办法
	 * @param fileName assets下的文件名
	 * @return absolutePath copy文件到可写目录,并返回绝对路径
	 *
	 * 有时会从其他的文件浏览器获取路径,这时根据路径去数据库取文件时会发现不成功,
	 * 原因是由于android的文件浏览器太多,各自返回的路径不统一,
	 * 而android本身的数据库中的路径是绝对路径,即"/mnt"开头的路径。
	 */
	private String copyAssetAndWrite(String fileName){
		try {
			File cacheDir=getCacheDir();
			if (!cacheDir.exists()){
				cacheDir.mkdirs();
			}
			File outFile =new File(cacheDir,fileName);
			if (!outFile.exists()){
				boolean res=outFile.createNewFile();
				if (!res){
					return null;
				}
			} else {
				if (outFile.length()>10){//表示已经写入一次
					return outFile.getPath();
				}
			}
			InputStream is=getAssets().open(fileName);
			FileOutputStream fos = new FileOutputStream(outFile);
			byte[] buffer = new byte[1024];
			int byteCount;
			while ((byteCount = is.read(buffer)) != -1) {
				fos.write(buffer, 0, byteCount);
			}
			fos.flush();
			is.close();
			fos.close();
			return outFile.getPath();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

  

原文地址:https://www.cnblogs.com/lyonwu/p/14089963.html