程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> 硅谷新聞10--數據緩存,硅谷10--緩存

硅谷新聞10--數據緩存,硅谷10--緩存

編輯:JAVA綜合教程

硅谷新聞10--數據緩存,硅谷10--緩存


1.向SharedPreferences 中存儲字符串

/**
 * 緩存文本數據
 *
 * @param context
 * @param key
 * @param value
 */
public static void putString(Context context, String key, String value) {
	if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
		///mnt/sdcard/beijingnews/files/llkskljskljklsjklsllsl
		try {
			String fileName = MD5Encoder.encode(key);//llkskljskljklsjklsllsl
			///mnt/sdcard/beijingnews/files/llkskljskljklsjklsllsl
			File file = new File(Environment.getExternalStorageDirectory() + "/beijingnews/files", fileName);
			File parentFile = file.getParentFile();//mnt/sdcard/beijingnews/files
			if (!parentFile.exists()) {
				//創建目錄
				parentFile.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			//保存文本數據
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			fileOutputStream.write(value.getBytes());
			fileOutputStream.close();

		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e("文本數據緩存失敗");
		}
	} else {
		SharedPreferences sp = context.getSharedPreferences("atguigu", Context.MODE_PRIVATE);
		sp.edit().putString(key, value).commit();
	}
}

  

2.從SharedPreferences 中獲取存儲的字符串

/**
 * 獲取緩存的文本信息
 *
 * @param context
 * @param key
 * @return
 */
public static String getString(Context context, String key) {
	String result = "";
	if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
		try {
			String fileName = MD5Encoder.encode(key);//llkskljskljklsjklsllsl
			///mnt/sdcard/beijingnews/files/llkskljskljklsjklsllsl
			File file = new File(Environment.getExternalStorageDirectory() + "/beijingnews/files", fileName);
			if (file.exists()) {
				FileInputStream is = new FileInputStream(file);
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int length;
				while ((length = is.read(buffer)) != -1) {
					stream.write(buffer, 0, length);
				}
				is.close();
				stream.close();
				result = stream.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.e("圖片獲取失敗");
		}
	} else {
		SharedPreferences sp = context.getSharedPreferences("atguigu", Context.MODE_PRIVATE);
		result = sp.getString(key, "");
	}
	return result;
}

  

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved