Android中資料存放區方式一:檔案形式

來源:互聯網
上載者:User

Android中資料存放區方式一:檔案形式

總結在Android中,一共有資料存放區的5種方式。今天做一個筆記的整理。關於以檔案形式如何來儲存資料。

1.在activity_main.xml設計好布局

2.在MainActivity.class擷取使用者輸入的檔案名稱和檔案資訊,儲存檔案。

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());            }}

   /**     * 如果這個類不需要被繼承,加個final關鍵字來終結它。     */    private final class saveFileListener implements OnClickListener{@Overridepublic 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();}
     }}

3.在業務層,FileSerivice處理如何儲存檔案內容。

 

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。

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.