Android 文件读写及文件下载操作

fmms 12年前

一,说明:

        这几天做一个功能需要在手机上创建一个文件夹,然后往里面存储一些文件,首先得考虑用户有没有sdcard,如果有就在sdcard上创建一个指定的文件夹,如果没有则在你的工程所在的目录“/data/data/你的包名”下创建文件夹。用到的方法是:

首先判断sdcard是否插入
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
然后根据是否插入状态指定目录
if (SdcardHelper.isHasSdcard()) {
sDir = SDCARD_DIR;
} else {
sDir = NOSDCARD_DIR;
}
然后是创建文件夹
File destDir = new File(sDir);
if (!destDir.exists()) {
destDir.mkdirs();
}
问题是:刚开始我的文件夹的目录是按照windows方式的例如"\sdcard\tempdir"结果运行后也不报错但是怎么也创建不了文件夹,后面想到应该是按linux格式的目录,改为"/sdcard/tempdir"后即可成功创建。
因为之前创建文件都是按照windows方式例如"\sdcard\test.txt"调用
new File("\\sdcard\\test.txt").createNewFile();创建而且可以成功,所以目录就没考虑。
经验证创建文件夹使用windows或者linux的目录结构都可以,而目录的话必须用linux的格式。
最后我看网上说要加入以下权限:
<!--往sdcard中写入数据的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<!--在sdcard中创建/删除文件的权限 -->

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>

二,实例

package demo.filerw.service;   import java.io.ByteArrayOutputStream;   import java.io.File;   import java.io.FileInputStream;   import java.io.FileOutputStream;   import android.content.Context;   import android.os.Environment;   /**    * 文件操作类    * @author janrone    * @website http://hujl.sinaapp.com    */   public class FileService {       private Context context;       public FileService(Context context) {           this.context = context;       }       //存储数据到文件       public void saveName(String name) throws Exception{           //context.getFilesDir();// 得到存放文件的系统目录 /data/data/<package name>/files           //context.getCacheDir(); //缓存目录  /data/data/<package name>/cache           FileOutputStream outputStream=context.openFileOutput(“deomfilerw.txt”, Context.MODE_APPEND);           outputStream.write(name.getBytes());           outputStream.close();       }       //存储数据到sdcard       public void saveNameToSDCard(String name) throws Exception{           Environment.getExternalStorageDirectory(); //得到sdcard目录           File file=new File(“/sdcard”,”demosdcard.txt”);           FileOutputStream outputStream=new FileOutputStream(file);           outputStream.write(name.getBytes());           outputStream.close();       }       // 读取数据       public String getName() throws Exception{           FileInputStream inputStream=context.openFileInput(“deomfilerw.txt”);           ByteArrayOutputStream outStream=new ByteArrayOutputStream();           byte[] buffer=new byte[1024];           int len=0;           while ((len=inputStream.read(buffer))!=-1){               outStream.write(buffer, 0, len);           }           outStream.close();           byte[] data=outStream.toByteArray();           String name=new String(data);           return name;       }   } 
三,应用实例(webView下载监听)
mWebView.setDownloadListener(new DownloadListener(){//监听下载                         public void onDownloadStart(String url, String userAgent, String contentDisposition,String mimetype, long contentLength)                           {                                 Toast.makeText(MainActivity.this,"下载中", Toast.LENGTH_SHORT).show();                                 downloadFile(url, mimetype, mimetype, mimetype, contentLength);                         }                                           });        }        private void downloadFile(String url,String userAgent, String contentDisposition,String mimetype, long contentLength) {             FileOutputStream fos;         boolean hasSD = Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED); //是否存在SD卡           Toast.makeText(MainActivity.this,"下载中开始", Toast.LENGTH_SHORT).show();           String filename =URLUtil.guessFileName(url,contentDisposition, mimetype);           try {                  if(hasSD)                  {                       File fileName=new File( Environment.getExternalStorageDirectory().getPath(),filename);                       fos = new FileOutputStream(fileName);                   }                   else                   {                       fos = this.openFileOutput(filename, Context.MODE_APPEND);                   }                                          URL url2 = new URL(url);                          HttpURLConnection conn = (HttpURLConnection) url2.openConnection();                          conn.setDoInput(true);                          conn.connect();                          if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {                                  InputStream is = conn.getInputStream();                                                                                                                        int len = 0;                                  byte[] buf = new byte[1024];                                  while ((len = is.read(buf)) != -1) {                                          fos.write(buf, 0, len);                                  }                                  is.close();                                  fos.close();                              Toast.makeText(MainActivity.this,"结束"+filename, Toast.LENGTH_SHORT).show();                          } else {                                    Toast.makeText(MainActivity.this,"下载错误", Toast.LENGTH_SHORT).show();                                   }                  } catch (Exception e) {                      Toast.makeText(MainActivity.this,"下载有错"+e.toString(), Toast.LENGTH_SHORT).show();                  }                                }