要往SDCard存放文件,程序必須先判斷手機是否裝有SDCard,並且可以進行讀寫。
注意:訪問SDCard必須在AndroidManifest.xml中加入訪問SDCard的權限
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File sdCardDir = Environment.getExternalStorageDirectory();//獲取SDCard目錄
File saveFile = new File(sdCardDir, “hello.txt”);
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("test".getBytes());
outStream.close();
}
Environment.getExternalStorageState()方法用於獲取SDCard的狀態,如果手機裝有SDCard,並且可以進行讀寫,那麼方法返回的狀態等於Environment.MEDIA_MOUNTED。
Environment.getExternalStorageDirectory()方法用於獲取SDCard的目錄,當然要獲取SDCard的目錄,你也可以這樣寫:
File sdCardDir = new File("/mnt/sdcard"); //獲取SDCard目錄
File saveFile = new File(sdCardDir, "itcast.txt");
//上面兩句代碼可以合成一句: File saveFile = new File("/mnt/sdcard/hello.txt");
FileOutputStream outStream = new FileOutputStream(saveFile);
outStream.write("test".getBytes());
outStream.close();