總結在Android中,一共有數據存儲的5種方式。今天做一個筆記的整理。關於以文件形式如何來保存數據。
1.在activity_main.xml設計好佈局
2.在MainActivity.class獲取用戶輸入的文件名和文件信息,保存文件。
1
2
3
4
5
6
7
8
9
10
11
|
public
class
MainActivity extends
Activity { private
Button saveBtn; @Override protected
void
onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); saveBtn
= (Button)findViewById(R.id.fileSaveBtn); saveBtn.setOnClickListener( new
saveFileListener()); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/** *
如果這個類不需要被繼承,加個final關鍵字來終結它。 */ private
final
class
saveFileListener implements
OnClickListener{ @Override public
void
onClick(View v) { EditText
fileNameText = (EditText)findViewById(R.id.inputName); EditText
fileContentText = (EditText)findViewById(R.id.inputContext); String
fileName = fileNameText.getText().toString(); String
fileContent = fileContentText.getText().toString(); FileService
fileService = new
FileService(getApplicationContext()); try
{ //保存到手機的內存上 fileService.saveFilePrivate(fileName,fileContent); }
catch
(Throwable e) { Toast.makeText(MainActivity. this ,
R.string.fail, Toast.LENGTH_LONG).show(); e.printStackTrace(); } |
1
2
|
} } |
3.在業務層,FileSerivice處理如何保存文件內容。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
public
class
FileService { private
Context context; //生成構造器 public
FileService(Context context){ this .context
= context; } /** *
保存文件信息 *
@param fileName 文件名 *
@param fileContent 文件內容 *
@throws Throwable */ public
void
saveFilePrivate(String fileName,String fileContent) throws
Exception{ //採用輸出流對象,輸出我們所需要的數據。 //指出需要導出的位置openFileOutput(只接受文件名稱,不接受文件路徑, //用於指定文件的操作模式,行爲【追加方式】,【覆蓋形式】 //文件有一個訪問權限的控制,針對擁有者,針對其他用戶的訪問權限 //私有操作模式:創建出來文件的只能被本應用訪問,其他應用無法訪問該文件。 //
其次私有模式創建出來的文件會覆蓋原有的文件內容。 //
默認保存在,當前應用包所在的下的files文件夾下。 FileOutputStream
outputStream = context.openFileOutput(lmfcast.txt,Context.MODE_PRIVATE); //追加方式 //FileOutputStream
outputStream = context.openFileOutput(lmfcast.txt,Context.MODE_APPEND); write(fileContent,
outputStream); } private
void
write(String fileContent, FileOutputStream outputStream) throws
IOException { outputStream.write(fileContent.getBytes()); outputStream.close(); } } |
4.源碼運行截圖:
學習總結:
1.文件保存方式,是採用java的IO流技術。
2.文件的訪問模式,分爲private和append。
3.文件操作行爲分爲:private,apend,read,write,read+write。