Android中保存文件到内部存储器
1 public static void saveDataToPrivateFile(Context context, String data, int mode, String fileName) { 2 FileOutputStream fileOutputStream = null; 3 BufferedWriter bufferedWriter = null; 4 5 try { 6 fileOutputStream = context.openFileOutput(fileName, mode); 7 bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream)); 8 bufferedWriter.write(data); 9 } catch (IOException e) { 10 e.printStackTrace(); 11 } finally { 12 try { 13 if (bufferedWriter != null) { 14 bufferedWriter.close(); 15 } 16 } catch (IOException e) { 17 e.printStackTrace(); 18 } 19 } 20 } 21 22 public static String loadDataFromPrivateFile(Context context, String fileName) { 23 FileInputStream fileInputStream = null; 24 BufferedReader bufferedReader = null; 25 StringBuilder stringBuilder = new StringBuilder(); 26 27 try { 28 fileInputStream = context.openFileInput(fileName); 29 bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream)); 30 String result = ""; 31 while ((result = bufferedReader.readLine()) != null) { 32 stringBuilder.append(result); 33 } 34 } catch (IOException e) { 35 e.printStackTrace(); 36 } finally { 37 if (bufferedReader != null) { 38 try { 39 bufferedReader.close(); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 } 44 } 45 46 return stringBuilder.toString(); 47 } 48 49 public static boolean deletePrivateFile(Context context, String fileName) { 50 try { 51 return context.deleteFile(fileName); 52 } catch (Exception e) { 53 e.printStackTrace(); 54 return false; 55 } 56 }