Android 文件讀寫及文件下載操作

fmms 12年前發布 | 41K 次閱讀 Android Android開發 移動開發

一,說明:

        這幾天做一個功能需要在手機上創建一個文件夾,然后往里面存儲一些文件,首先得考慮用戶有沒有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();
                }



        }

 本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!