數據存儲之文件存儲

//1.文件的路徑
        
//建立文件
File file = new File("/mnt/sdcard/test");
	if (!file.exists()) {
		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		   }
		}else {
			Toast.makeText(MainActivity.this, "文件已存在", 1000);
		}

//刪除文件
file.delete();

//得到內部文件路徑
File file = this.getFilesDir();

//得到內部緩存路徑
File file = this.getCacheDir();

//自定義權限路徑 /data/data/<包名>/app_imooc
File file = this.getDir("imooc", MODE_PRIVATE);

//得到外部文件路徑
File file = this.getExternalFilesDir(type);

//得到外部緩存路徑
File file = this.getExternalCacheDir();


==================

//2.文件的讀寫
public class MainActivity extends Activity {
	EditText edt;
	Button but;
	TextView contentvalue;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edt = (EditText) findViewById(R.id.editText1);
		but = (Button) findViewById(R.id.write);
		contentvalue = (TextView) findViewById(R.id.contentvalue);
		but.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				WriteFiles(edt.getText().toString());
				contentvalue.setText(readFiles());
				
			}
		});
	}
	//文件寫入
	public void WriteFiles(String content){
		 try {
			FileOutputStream fos = openFileOutput("a.txt", MODE_WORLD_READABLE+MODE_WORLD_WRITEABLE);
			 fos.write(content.getBytes());
			 fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
	}
	//文件寫出
	public String readFiles(){
		String content = null;
		 try {
			FileInputStream fis= openFileInput("a.txt");
			 ByteArrayOutputStream baos =  new ByteArrayOutputStream();
			byte [] buffer =  new byte[1024];
			int len = 0;
           //每次從fis中讀取一個字節buffer,直到把fis讀完
			while ((len=fis.read(buffer))!=-1) {
				baos.write(buffer, 0, len);
			}
			content = baos.toString();
			fis.close();
			baos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return content;
	}
}

相關文章
相關標籤/搜索