【Android】檔案讀寫及檔案下載操作

來源:互聯網
上載者:User

一,說明:

        這幾天做一個功能需要在手機上建立一個檔案夾,然後往裡面儲存一些檔案,首先得考慮使用者有沒有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();                }                        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.