標籤:android io
openFileOutput和openFileInput 擷取手機記憶體中的檔案而不是SD卡中的。
Context提供了兩個方法來開啟本應用程式的資料檔案夾裡的檔案I/O流。
openFIleInput(String name):name檔案對應的輸入資料流
openFileOutput(String name,int mode):name檔案對應的輸出資料流
其中輸出資料流中的第二個參數表示開啟檔案的模式,也可以稱作許可權:
MODE_PRIVATE:該檔案只能被當前程式讀寫
MODE_APPEND:以追加的方式開啟該檔案,可以追加內容
MODE_WORLD_READABLE:該檔案中的內容可以被其他程式讀取
MODE_WORLD_WRITEABLE:該檔案中的內容可以被其他程式讀、寫。
除此之外,Context還提供了如下幾個方法來訪問應用程式的資料檔案夾:
getDir(String name,int mode):在應用程式的資料檔案夾下擷取或建立name對應的子目錄
File getFilesDir():擷取應用程式的資料檔案夾的絕對路徑
String[] fileList ():返回該應用程式的資料檔案夾下的全部檔案
deleteFile(String ): 刪除該應用程式的資料檔案夾下的指定檔案
public class MainActivity extends Activity {private EditText et;private Button saveButton, readButton;private TextView show;private boolean MyWrite() {try {FileOutputStream fos = openFileOutput("data",Context.MODE_WORLD_READABLE);String content = et.getText().toString();fos.write(content.getBytes());fos.flush();fos.close();Toast.makeText(MainActivity.this, "成功", 1).show();return true;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return false;}private boolean MyRead() {try {FileInputStream fis = openFileInput("data");byte buff[] = new byte[1024];StringBuffer sb = new StringBuffer();int hasread = 0;while ((hasread = fis.read(buff)) != -1) {sb.append(new String(buff));}fis.close();show.setText(sb.toString());Toast.makeText(MainActivity.this, sb.toString(), 1).show();return true;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return false;}protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);et = (EditText) findViewById(R.id.edittext);saveButton = (Button) findViewById(R.id.save);readButton = (Button) findViewById(R.id.red);show = (TextView) findViewById(R.id.show);saveButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubMyWrite();}});readButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubMyRead();}});}}
Android---35---openFileInput、openFileOutput擷取手機記憶體中的資料