MainActivity.java
import android.content.Context; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.view.View.OnClickListener; import android.widget.Toast; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; public class MainActivity extends ActionBarActivity { private Button btnTxtRead; private Button btnTxtWrite; private Button btnFileDel; private EditText txtWrite; private TextView txtRead; String fileName = "dateRec.dat"; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtWrite = (EditText) findViewById(R.id.editText); txtRead = (TextView) findViewById(R.id.textView); btnTxtRead = (Button) findViewById(R.id.btnRead); btnTxtWrite = (Button) findViewById(R.id.btnWrite); btnFileDel = (Button) findViewById(R.id.btnDel); btnTxtRead.setOnClickListener(btnListener); btnTxtWrite.setOnClickListener(btnListener); btnFileDel.setOnClickListener(btnListener); } private void writer() { FileOutputStream fos = null; try { fos = openFileOutput(fileName, Context.MODE_PRIVATE); fos.write(txtWrite.getText().toString().getBytes()); fos.close(); File file = new File(getFilesDir() + "/" + fos); Toast.makeText(getApplicationContext(), file.getAbsolutePath(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } private void reader() { FileInputStream fos = null; BufferedInputStream buffered = null; txtRead.setText(""); try { fos = openFileInput(fileName); buffered = new BufferedInputStream(fos); byte[] buffbyte = new byte[200]; txtRead.setText(""); do { int flag = buffered.read(buffbyte); if (flag == -1) { break; } else { txtRead.append(new String(buffbyte), 0, flag); } }while (true); buffered.close(); } catch (Exception e) { e.printStackTrace(); } } private void fileDel() { File file = new File(getFilesDir() + "/" + fileName); if (file.exists()){ file.delete(); Toast.makeText(getBaseContext(), "File deleted", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getBaseContext(), "File doesn't exist", Toast.LENGTH_SHORT).show(); } } private OnClickListener btnListener = new OnClickListener() { public void onClick(View v) { switch (v.getId()) { case R.id.btnRead: try { Toast.makeText(getApplicationContext(), "Read button pressed", Toast.LENGTH_SHORT).show(); reader(); } catch (Exception e) { e.printStackTrace(); } break; case R.id.btnWrite: try { Toast.makeText(getApplicationContext(), "Write button pressed", Toast.LENGTH_SHORT).show(); writer(); } catch (Exception e) { e.printStackTrace(); } break; case R.id.btnDel: try { Toast.makeText(getApplicationContext(), "Del button pressed", Toast.LENGTH_SHORT).show(); fileDel(); } catch (Exception e) { e.printStackTrace(); } break; } } }; }
謝謝您的資源提供!!很有幫助^_^_b
回覆刪除