android內存讀寫與sharedPreferences

安卓內存讀寫

    安卓對於各自的app都有相應的存儲內存空間,在該空間下,沒有讀寫權限限制,可以隨意操作讀寫。

    跨過了該區域,就要添加用戶讀寫權限了。

    

public void getPath(View v) {
		String rootPath = "data/data/com.example.iostorage";
		editText.setText(rootPath);
		editText.setSelection(editText.getText().toString().length());
	}

	public void readFile(View v) {
		try {
			File file = new File(editText.getText().toString(), "aa.txt");

			if (!file.exists()) {
				Toast.makeText(this, "file not find", 1).show();
				return;
			}

			FileInputStream fis = new FileInputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) != -1) {
				String string = new String(buffer, 0, len);
				System.out.println(string);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void writeFile(View v) {
		try {
			File file = new File(editText.getText().toString(), "aa.txt");
			FileOutputStream fos = new FileOutputStream(file);
			fos.write("username=hls&&password=123".getBytes());
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    

系統有自帶的getCacheDir與getFilesDir,可以存儲在指定路徑下。

public void getFileDir(View v) {
		String rootPath = this.getFilesDir().getPath();
		editText.setText(rootPath);
		editText.setSelection(editText.getText().toString().length());
	}

	public void getSDcard1(View v) {
		String rootPath = "/mnt/sdcard";
		editText.setText(rootPath);
		editText.setSelection(editText.getText().toString().length());
	}

也可以存儲在sdcard上,操作如下

public void getSDcard1(View v) {
		String rootPath = "/mnt/sdcard";
		editText.setText(rootPath);
		editText.setSelection(editText.getText().toString().length());
	}

	public void getSDcard2(View v) {
		// Environment.getDataDirectory(); /data
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			Toast.makeText(this, "sdCard can't be used", 1).show();
			return;
		}

		System.out.println(Environment.getDownloadCacheDirectory());

		String rootPath = Environment.getExternalStorageDirectory().getPath();
		editText.setText(rootPath);
		editText.setSelection(editText.getText().toString().length());
	}

連個方法都可以獲取sdcard路徑

    

關於SharedPreferences,是系統指定的一個存儲位置,不需要設定路徑,就可以實現讀寫操作,存儲文件以.xml的格式存儲。

public void shareRead(View v) {
		SharedPreferences sp = getSharedPreferences("aa.txt",
				Context.MODE_PRIVATE);
		String string1 = sp.getString("username", "xx");
		String string2 = sp.getString("password", "xx");
	}

	public void shareWrite(View v) {
		SharedPreferences sp = getSharedPreferences("aa.txt",
				Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putString("username", "hls");
		edit.putString("password", "123");
		edit.commit();
	}

最後系統內的文件名是aa.txt.xml


寫了出來後文件路徑如上

在app對應的文件夾下面

    

時間後面的drwxr-x--x意思是文件的操作權限

第一個字母d代表裏面還有文件夾

之後的rwx分別代表可讀、可寫、可運行

    


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章