SD卡的读写是我们在开发android 应用程序过程中最常见的操作。下面介绍SD卡的读写操作方式:
1. 获取SD卡的根目录
[java] view plaincopy
- String sdCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
2. 在SD卡上创建文件夹目录
[java] view plaincopy
- /**
- * 在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卡上创建文件
[java] view plaincopy
- /**
- * 在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卡的某个目录
[java] view plaincopy
- /**
- * 判断SD卡上文件是否存在
- */
- public boolean isFileExist(String fileName, String path)
- {
- File file = new File(sdCardRoot + path + File.separator + fileName);
- return file.exists();
- }
5.将数据写入到SD卡指定目录文件
[java] view plaincopy
- <span style="white-space:pre"> </span>/**
- * 写入数据到SD卡中
- */
- 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]; //每次写2K数据
- 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
时间: 2024-10-28 22:05:32