來源:https://blog.csdn.net/anjingshuai/article/details/84682779
開發過程中碰到將文件存儲到手機中時,要先判斷是否有sd卡,如下所示
-
// 判斷是否有SD卡
-
private static boolean ExistSDCard() {
-
if (android.os.Environment.getExternalStorageState().equals(
-
android.os.Environment.MEDIA_MOUNTED)) {
-
return true;
-
} else
-
return false;
-
}
如果存在,則要獲取sd卡的根目錄路徑,在目錄下創建新的文件夾,sd卡根目錄路徑如下:
-
public static String SDCARDPATH = Environment.getExternalStorageDirectory()
-
.getPath();
然后是將要復制的文件寫到sd卡下新建的文件夾內,代碼如下:
-
private void copyzipfileToLocalDir(final String path, final String filename) {
-
File file = new File(path);
-
if (file.exists()) {
-
Uri uri = Uri.fromFile(file);
-
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
-
intent.setClass(MainActivity. this, TestActivity.class);
-
startActivity(intent);
-
return;
-
}
-
pdlog = new ProgressDialog(this);
-
pdlog.setMessage( "正在復制文件...");
-
pdlog.show();
-
-
new Thread() {
-
public void run() {
-
try {
-
InputStream input = getApplicationContext().getAssets()
-
.open(filename);
-
File f = new File(path);
-
if (f.exists()) {
-
return;
-
}
-
File file = f.getParentFile();
-
// SDCARD/CN/ZNsql====================path
-
if (!file.exists()) {
-
file.mkdir();
-
}
-
FileOutputStream fout = new FileOutputStream(f);
-
byte[] buff = new byte[1024];
-
int len = 0;
-
while ((len = input.read(buff)) > 0) {
-
fout.write(buff, 0, len);
-
}
-
fout.close();
-
input.close();
-
-
} catch (Exception e) {
-
e.printStackTrace();
-
}
-
handler.sendEmptyMessage( 1);
-
};
-
}.start();
-
}
-
private Handler handler = new Handler() {
-
-
public void handleMessage(android.os.Message msg) {
-
switch (msg.what) {
-
case 1:
-
if (pdlog != null) {
-
if (pdlog.isShowing()) {
-
pdlog.cancel();
-
}
-
;
-
}
-
// jump
-
File file = new File(SDCARDPATH+ "androidtest.pdf");
-
-
if (file.exists()) {
-
Uri uri = Uri.fromFile(file);
-
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
-
intent.setClass(MainActivity. this, TestActivity.class);
-
startActivity(intent);
-
}
-
-
break;
-
default:
-
break;
-
}
-
};
-
};
這樣就將assets下的文件寫入了外置sd卡,對於一些不支持外置存儲卡的Android手機,我們可以將文件寫入機身內存,也就是俗稱的ROM中,RomPath= Environment.getDataDirectory().getPath();當判斷到沒有外置sd卡時就可以把path換成這個RomPath即可,這樣就完成了將文件寫入機身內存中。