SD卡的读写是我们在开发android 应用程序过程中最常见的操作。下面介绍SD卡的读写操作方式:
1. 获取SD卡的根目录
- String sdCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
2. 在SD卡上创建文件夹目录
- public File createDirOnSDCard(String dir)
- {
- File dirFile = new File(sdCardRoot + File.separator + dir +File.separator);
- Log.v("createDirOnSDCard", sdCardRoot + File.separator + dir +File.separator);
- dirFile.mkdirs();
- return dirFile;
- }
3. 在SD卡上创建文件
- public File createFileOnSDCard(String fileName, String dir) throws IOException
- {
- File file = new File(sdCardRoot + File.separator + dir + File.separator + fileName);
- Log.v("createFileOnSDCard", sdCardRoot + File.separator + dir + File.separator + fileName);
- file.createNewFile();
- return file;
- }
4.判断文件是否存在于SD卡的某个目录
- public boolean isFileExist(String fileName, String path)
- {
- File file = new File(sdCardRoot + path + File.separator + fileName);
- return file.exists();
- }
5.将数据写入到SD卡指定目录文件
- <span style="white-space:pre"> </span>
- public File writeData2SDCard(String path, String fileName, InputStream data)
- {
- File file = null;
- OutputStream output = null;
-
- try {
- createDirOnSDCard(path);
- file = createFileOnSDCard(fileName, path);
- output = new FileOutputStream(file);
- byte buffer[] = new byte[2*1024];
- int temp;
- while((temp = data.read(buffer)) != -1 )
- {
- output.write(buffer,0,temp);
- }
- output.flush();
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- finally{
- try {
- output.close();
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
-
- return file;
- }
one more important thing:
对SD卡的操作,必须要申请权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
转自:http://blog.csdn.net/newjerryj/article/details/8829179
Android入门开发之SD卡读写操作(转)
原文:http://www.cnblogs.com/SharkBin/p/4212859.html