Android-檔案儲存體

來源:互聯網
上載者:User

標籤:

目標效果:

  

程式運行,顯示一輸入框和按鈕,在輸入框輸入內容點擊按鈕會提示儲存成功,關閉程式,再次開啟會在輸入框顯示剛才輸入的內容,並提示英文。


1.activity_main.xml頁面放置兩個控制項。

activity_main.xml頁面:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <EditText        android:id="@+id/etInput"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_above="@+id/btClick"        android:layout_centerHorizontal="true"        android:layout_marginBottom="34dp"        android:ems="10"        android:hint="請輸入想儲存的內容" >        <requestFocus />    </EditText>    <Button        android:id="@+id/btClick"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:onClick="save"        android:text="確定" /></RelativeLayout>


2.建立FileService.java類,編寫儲存和讀取方法。

FileService.java頁面:

package com.example.file;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import android.content.Context;public class FileService {private Context context;public FileService(Context context){this.context=context;}/*建立檔案儲存內容*/public void save(String fileName,String content){BufferedWriter bw=null;try {//開啟檔案,得到檔案輸出資料流(位元組流),參數一為檔案名稱,參數二為開啟檔案,為私人FileOutputStream fos=context.openFileOutput(fileName,context.MODE_PRIVATE);//OutputStreamWriter把位元組流轉換成字元流,BufferedWriter建立緩衝區bw=new BufferedWriter(new OutputStreamWriter(fos));//往緩衝區寫入內容bw.write(content);} catch (FileNotFoundException e) {e.printStackTrace();}catch (IOException e) {e.printStackTrace();}finally{try {if(bw!=null){bw.close();}} catch (IOException e) {e.printStackTrace();}}}/*開啟檔案讀取內容*/public String read(String fileName){String line;StringBuilder sb=new StringBuilder();BufferedReader br=null;try {FileInputStream fis=context.openFileInput(fileName);br=new BufferedReader(new InputStreamReader(fis));while((line=br.readLine())!=null){sb.append(line);}} catch (FileNotFoundException e) {e.printStackTrace();}catch (IOException e) {e.printStackTrace();}finally{try {if(br!=null){br.close();}} catch (IOException e) {e.printStackTrace();}}return sb.toString();}}


3.寫完儲存方法和讀取方法,可以先不寫MainActivity.java的代碼,先寫一個fileText.java類進行單元測試,檢測儲存方法和讀取方法是否有錯誤。

fileText.java頁面:

package com.example.text;import com.example.file.FileService;import android.test.AndroidTestCase;import android.util.Log;public class fileText extends AndroidTestCase{public void saveText(){FileService fileservice=new FileService(getContext());fileservice.save("out.txt","hello!");}public void readText(){FileService fileservice=new FileService(getContext());String s=fileservice.read("out.txt");Log.i("MainActivity","s="+s);}}


4.編寫完測試類別後,開始測試回合,兩個方法的運行方式都一樣。

5.測試回合後,如果在左上方出現綠色橫條,說明方法編寫無錯誤。
6.最後編寫MainActivity.java頁面,用於將儲存和讀取方法和控制項綁定。MainActivity.java頁面:
package com.example.file;import android.os.Bundle;import android.app.Activity;import android.view.View;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {private EditText etInput;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);/*擷取控制項方法*/getId();/*讀取檔案內容方法*/read();}/*讀取檔案內容方法*/private void read() {FileService fileservice=new FileService(this);String content=fileservice.read("myfile.txt");if(!content.isEmpty()){etInput.setText(content);etInput.setSelection(content.length());Toast.makeText(this,"Restoring succeeded",Toast.LENGTH_SHORT).show();}}/*點擊按鈕調用save方法*/public void save(View view){FileService fileservice=new FileService(this);String content=etInput.getText().toString();fileservice.save("myfile.txt",content);Toast.makeText(this,"儲存成功",Toast.LENGTH_SHORT).show();}/*擷取控制項方法*/private void getId() {etInput=(EditText) findViewById(R.id.etInput);}}


7.運行後可以顯示目標效果,可以從環境中看到檔案儲存目錄,還是需要在模擬器環境下查看。



8.按照以前博文介紹的方法,可以導儲存到案頭查看檔案中的內容,可以發現out.txt檔案中是測試時儲存的“hello!”,myfile.txt檔案中是運行時輸入的“123456”。








Android-檔案儲存體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.