1. 程式人生 > >在SD卡建立資料夾、寫入檔案、讀取檔案

在SD卡建立資料夾、寫入檔案、讀取檔案

    <!-- SD卡內建立資料夾 -->

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

//建立資料夾

if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
// 建立一個資料夾物件,賦值為外部儲存器的目錄
File sdcardDir =Environment.getExternalStorageDirectory();
//得到一個路徑,內容是sdcard的資料夾路徑和名字
String path=sdcardDir.getPath()+"/makeByHwh";
File path1 = new File(path);
if (!path1.exists()) {
path1.mkdirs();
Toast.makeText(getApplicationContext(), "成功建立資料夾", 0).show();
}else{
Toast.makeText(getApplicationContext(), "已經存在", 0).show();
}

}

//寫入資料

Writer writer = null;
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
// 建立一個資料夾物件,賦值為外部儲存器的目錄
File sdCard = Environment.getExternalStorageDirectory();
// 檢視LogCat,獲取的sd卡的絕對路徑為 /storage/sdcard
sdCard = new File(sdCard, "/makeByHwh");
if (!sdCard.exists()) {
sdCard.mkdirs();
}
sdCard = new File(sdCard, "s");
FileOutputStream out;
try {
out = new FileOutputStream(sdCard);
writer = new OutputStreamWriter(out);
String str = "來自儲存在內部儲存裝置的資料";
writer.write(str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

//讀取資料

BufferedReader reader = null;
StringBuilder data = new StringBuilder();
try {
File sdCard = Environment.getExternalStorageDirectory();
sdCard = new File(sdCard, "/makeByHwh/" + "s");
FileInputStream in = new FileInputStream(sdCard);
reader = new BufferedReader(new InputStreamReader(in));
String line = new String();
while ((line = reader.readLine()) != null) {
data.append(line);
}
Toast.makeText(getApplicationContext(), data, 0).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "沒有發現數據", 0).show();
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}