文件方式保存数据,保存路径为/data/data/<packagename>/files/。有两种模式:MODE_PRIVATE 和 MODE_APPEND,其中 MODE_PRIVATE 是默认的操作模式,表示当指定同样文件名的时候,所写入的内容将会覆盖原文件中的内容,而 MODE_APPEND 则表示如果该文件已存在就往文件里面追加内容,不存在就创建新文件。
1 public void save() { 2 String data = "Data to save"; 3 FileOutputStream out = null; 4 BufferedWriter writer = null; 5 try { 6 out = openFileOutput("data", Context.MODE_PRIVATE); 7 writer = new BufferedWriter(new OutputStreamWriter(out)); 8 writer.write(data); 9 } catch (IOException e) { 10 e.printStackTrace(); 11 } finally { 12 try { 13 if (writer != null) { 14 writer.close(); 15 } 16 } catch (IOException e) { 17 e.printStackTrace(); 18 } 19 } 20 }
1 public String load() { 2 FileInputStream in = null; 3 BufferedReader reader = null; 4 StringBuilder content = new StringBuilder(); 5 try { 6 in = openFileInput("data"); 7 reader = new BufferedReader(new InputStreamReader(in)); 8 String line = ""; 9 while ((line = reader.readLine()) != null) { 10 content.append(line); 11 } 12 } catch (IOException e) { 13 e.printStackTrace(); 14 } finally { 15 if (reader != null) { 16 try { 17 reader.close(); 18 } catch (IOException e) { 19 e.printStackTrace(); 20 } 21 } 22 } 23 return content.toString(); 24 }
时间: 2024-10-14 14:52:08