<!-- 在SD卡中创建和删除文件的权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 在SD卡中写入数据的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED){ }
写入SD卡数据时,我们要先判断SD卡是否挂载正常,然后新建一个文件File,再新建一个字节输出流,之后我们可以直接通过该输出流写入字节数据,或者可以将其包装成一个字符输出流Wirter再进行写入操作,注意在写入数据后要对输出流进行flush()操作,强制将缓冲区的内容输出,最后关闭输出流。
操作代码如下:
try {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "info.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
outputStreamWriter.write("This is a text");
outputStreamWriter.flush();
outputStreamWriter.close();
fileOutputStream.close();
Toast.makeText(MainActivity.this, "写入成功", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "请检查SD卡是否存在", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "发生错误,写入失败", Toast.LENGTH_LONG).show();
}
读取SD卡数据时,我们可以先新建一个文件File,然后新建一个字节输入流,之后我们可以将其包装成一个字符输入流Reader再进行读取操作。
操作代码如下:
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
char[] input = new char[fileInputStream.available()];
inputStreamReader.read(input);
inputStreamReader.close();
fileInputStream.close();
String data= new String(input);
Toast.makeText(MainActivity.this, data, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "请检查SD卡是否存在", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(MainActivity.this, "发生错误,读取失败", Toast.LENGTH_LONG).show();
}