將資料以檔案的形式儲存
阿新 • • 發佈:2019-01-11
廢話不多說,直接上程式碼,私有檔案在data/data/appName/下,不能將檔案拷貝
/** * 將資料寫入到私有檔案中 * @param context * @param data * @param fileName */ private void saveDataToFile(Context context, String data, String fileName) { FileOutputStream fileOutputStream = null; BufferedWriter bufferedWriter = null; try { fileOutputStream = context.openFileOutput(fileName,Context.MODE_APPEND); bufferedWriter = new BufferedWriter( new OutputStreamWriter(fileOutputStream)); bufferedWriter.write(data); Toast.makeText(context, "儲存的資料為"+data, Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace();} finally { try { if (bufferedWriter != null) { bufferedWriter.close(); } } catch (IOException e) { e.printStackTrace(); } } }
/** * 從檔案中讀取資料 * @param context context* @param fileName 檔名 * @return 從檔案中讀取的資料 */ private String loadDataFromFile(Context context, String fileName) { FileInputStream fileInputStream = null; BufferedReader bufferedReader = null; StringBuilder stringBuilder = new StringBuilder(); try { /** * 注意這裡的fileName不要用絕對路徑,只需要檔名就可以了,系統會自動到data目錄下去載入這個檔案 */ fileInputStream = context.openFileInput(fileName); bufferedReader = new BufferedReader( new InputStreamReader(fileInputStream)); String result = ""; while ((result = bufferedReader.readLine()) != null) { stringBuilder.append(result); } } catch (IOException e) { e.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } return stringBuilder.toString(); }
以文字形式儲存到指定資料夾可以進行拷貝
/** * 將資料以文字的形式儲存到指定目錄下 * @param bytes */ private void saveToPublic(byte[] bytes){ String status = Environment.getExternalStorageState(); if (status.equals(Environment.MEDIA_MOUNTED)){ try{ String filename = newDate(); File file = new File(Environment.getExternalStorageDirectory()+"/"+"ZRY",filename); if (!file.exists()){ File dir = new File(file.getParent()); dir.mkdirs(); } FileOutputStream outStream = new FileOutputStream(file+".txt",true); //檔案輸出流用於將資料寫入檔案 outStream.write(bytes); outStream.close(); //關閉檔案輸出流 }catch (Exception e){ e.printStackTrace(); } } }
/** * 返回一個時間的名稱 * @return */ public static String newDate(){ Time time = new Time(); time.setToNow(); int year = time.year; int month = time.month+1; int monthDay = time.monthDay; int hour = time.hour; int minute = time.minute; int second = time.second; return ""+year+month+monthDay+hour+minute+second; }