天天看點

Android--向SD卡讀寫資料

Android--向SD卡讀寫資料

// 向sd卡寫入資料  

    private void writesdcard(string str) {  

        try {  

            // 判斷是否存在sd卡  

            if (environment.getexternalstoragestate().equals(  

                    environment.media_mounted)) {  

                // 擷取sd卡的目錄  

                file sddire = environment.getexternalstoragedirectory();  

                fileoutputstream outfilestream = new fileoutputstream(  

                        sddire.getcanonicalpath() + "/test.txt");  

                outfilestream.write(str.getbytes());  

                outfilestream.close();  

                toast.maketext(this, "資料儲存到text.txt檔案了", toast.length_long)  

                        .show();  

            }  

        } catch (exception e) {  

            e.printstacktrace();  

        }  

    }  

    // 從sd卡中讀取資料  

    private void readsdcard() {  

        stringbuffer strsbuffer = new stringbuffer();  

            // 判斷是否存在sd  

                file file = new file(environment.getexternalstoragedirectory()  

                        .getcanonicalpath() + "/test.txt");  

                // 判斷是否存在該檔案  

                if (file.exists()) {  

                    // 打開檔案輸入流  

                    fileinputstream filer = new fileinputstream(file);  

                    bufferedreader reads = new bufferedreader(  

                            new inputstreamreader(filer));  

                    string st = null;  

                    while ((st = reads.readline()) != null) {  

                        strsbuffer.append(st);  

                    }  

                    filer.close();  

                } else {  

                    toast.maketext(this, "該目錄下檔案不存在", toast.length_long).show();  

                }  

        toast.maketext(this, "讀取到的資料是:" + strsbuffer.tostring() + "",  

                toast.length_long).show();  

}  

轉載:http://blog.csdn.net/chaoyu168/article/details/50721480