读写SD卡文件

权限





判断是否具备读写条件

如果手机存在SDcard,并且应用具有读写权限,则
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)返回true

路径

通过Environment.getExternalStorageDirectory()获取SDcard的根目录File
通过file.getCanonicalPath()获取规范化绝对路径
Tips:
1. getPath()定义路径,定义时为相对路径则返回相对路径;定义时为绝对路径则为绝对路径
2. getAbsolutePath()定义路径的绝对路径
3. getCanonicalPath规范化绝对路径

File file1 = new File(".\\test.txt");
file1.getPath();                //  .\test.txt
file1.getAbsolutePath();        //  E:\workspace\Test\.\test.txt
file1.getCanonicalPath();       //  E:\workspace\Test\test.txt

File file2 = new File("/sdcard/tlib/test.txt");
file2.getPath();                //  /sdcard/tlib/test.txt
file2.getAbsolutePath();        //  /sdcard/tlib/test.txt
file2.getCanonicalPath();       //  /sdcard/tlib/test.txt

目录

先判断目录是否存在,不存在则创建

File folder = new File(folderName);
if (!folder.exists()) {
    folder.mkdir();
}

文件读

获取文件输入流
FileInputStream fis = new FileInputStream(BasePath + folderName + fileName);
包装输入流
BufferedReader br = new BufferedReader(new InputStreamReader(fis));

文件写

FileOutputStream fileOutputStream = new FileOutputStream(BasePath + folderPath + fileName);
fileOutputStream.write(sb.toString().getBytes());

你可能感兴趣的:(读写SD卡文件)