android小功能實現之檔案讀寫

來源:互聯網
上載者:User

android小功能實現之檔案讀寫
建立一個Android工程。


一 布局
先看:


開啟main.xml修改內容如下:

                            

二 定義字串
開啟strings.xml新增內容如下:

    File    Settings    檔案名稱    檔案內容    儲存    儲存成功    儲存失敗    讀取    讀取成功    讀取失敗

三 功能實現
建立一個類FileService,用於檔案的讀寫,完整代碼如下:

public class FileService {    public Context context;       public  FileService(Context context){           this.context = context;       }    /**     * 儲存字串到檔案     * @param name 檔案名稱     * @param content 檔案內容     */    public void save(String name, String content) throws Exception{        // MODE_PRIVATE 建立出來的檔案,僅能被本應用訪問,而且新寫入的內容會覆蓋原來的內容         FileOutputStream os = context.openFileOutput(name, Context.MODE_PRIVATE);        // 預設儲存在/data/data//files目錄        os.write(content.getBytes());        os.close();    }    /***     * 讀取檔案內容     * @param name 檔案名稱     * @return     * @throws Exception     */    public String read(String name) throws  Exception{        FileInputStream is = context.openFileInput(name);        ByteArrayOutputStream os = new ByteArrayOutputStream();        byte[] buf = new byte[1024];        int len = 0;        while( (len = is.read(buf)) != -1){            os.write(buf,0, len);        }        byte[] data = os.toByteArray();        String content = new String(data);        return  content;    }}

四 測試代碼
修改MainActivity.java代碼如下:

    public EditText nameText;    public EditText saveContentText;    public EditText readContentText;    public Button button_read;    public String filename;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        nameText = (EditText)this.findViewById(R.id.filename);        saveContentText = (EditText)this.findViewById(R.id.save_file_content);        readContentText = (EditText)this.findViewById(R.id.read_file_content);        Button button_save = (Button) this.findViewById(R.id.button_save);        button_save.setOnClickListener(new ButtonSaveClickListener());        button_read = (Button) this.findViewById(R.id.button_read);        button_read.setClickable(false);        button_read.setOnClickListener(new ButtonReadClickListener());    }    private final class ButtonSaveClickListener implements View.OnClickListener{        public void onClick(View v){            String name = nameText.getText().toString();            String content = saveContentText.getText().toString();            FileService service = new FileService(getApplicationContext());            try {                filename = name;                service.save(name, content);                filename = name;                button_read.setClickable(true);                Toast.makeText(getApplicationContext(),R.string.save_success, Toast.LENGTH_LONG).show();            }catch (Exception e){                Toast.makeText(getApplicationContext(),R.string.save_fail, Toast.LENGTH_LONG).show();                e.printStackTrace();            }        }    }    private final class ButtonReadClickListener implements View.OnClickListener{        public void onClick(View v){            FileService service = new FileService(getApplicationContext());            try {                String content = service.read(filename);                readContentText.setText(content);                Toast.makeText(getApplicationContext(),R.string.read_success, Toast.LENGTH_LONG).show();            }catch (Exception e){                Toast.makeText(getApplicationContext(),R.string.read_fail, Toast.LENGTH_LONG).show();                e.printStackTrace();            }        }    }

運行結果



聯繫我們

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