安卓内存读写
安卓对于各自的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分别代表可读、可写、可运行
本文介绍了Android应用中如何进行内存读写操作,包括在应用的存储内存空间内自由读写,以及需要用户权限的跨区域读写。重点讲解了系统提供的getCacheDir和getFilesDir方法用于指定路径存储。此外,还详细阐述了SharedPreferences的使用,它是系统内置的存储位置,无需指定路径,以.xml格式保存数据,方便读写。
780

被折叠的 条评论
为什么被折叠?



