public static void initialize(Context context) { if (DNUtils.getRootDir() != null) { STORE = context.getSharedPreferences(STORE_NAME, Context.MODE_PRIVATE); final String rootPath = Environment.getExternalStorageDirectory() + "/" + DNUtils.getRootDir(); final String imagesPath = rootPath + "/images"; final String jsonsPath = rootPath + "/texts"; if (!STORE.contains(KEY_DIR_IMAGES) || !STORE.contains(KEY_DIR_IMAGES) || !STORE.contains(KEY_DIR_JSONS)) { final SharedPreferences.Editor editor = STORE.edit(); editor.putString(KEY_DIR_ROOT, rootPath); editor.putString(KEY_DIR_IMAGES, imagesPath); editor.putString(KEY_DIR_JSONS, jsonsPath); editor.putLong(KEY_SIZE, 0); editor.commit(); } File file = new File(rootPath); if (!file.exists()) file.mkdir(); file = new File(imagesPath); if (!file.exists()) file.mkdir(); file = new File(jsonsPath); if (!file.exists()) file.mkdir(); } }
// TODO read text file private static String readTextFromFile(File file) { try { InputStream is = new FileInputStream(file); Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { @SuppressWarnings("resource") Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } catch (Exception e) { e.printStackTrace(); DNUtils.logError(e.getMessage()); return null; } }
// TODO write text file private static boolean writeTextIntoFile(String text, String path) { FileWriter writer; try { File file = new File(path); boolean isExists = file.exists(); writer = new FileWriter(path, false); writer.write(text); writer.flush(); writer.close(); file = new File(path); if (!isExists) { long size = STORE.getLong(KEY_SIZE, 0); size += file.length(); STORE.edit().putLong(KEY_SIZE, size).commit(); } } catch (IOException e) { e.printStackTrace(); DNUtils.logError(e.getMessage()); return false; } return true; }
// TODO get text file public static String getText(String name) { String localPath = STORE.getString(KEY_DIR_JSONS, "") + "/" + DNUtils.toMD5(name); File file = new File(localPath); if (file.exists()) return readTextFromFile(file); return null; }
// TODO get local image path public static String getLocalPath(String url) { return STORE.getString(KEY_DIR_IMAGES, "") + "/" + DNUtils.toMD5(url); }