1.权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2.sd卡路径
SDCARD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();(先创建好所需要的文件夹及其对应的层级关系)
存储位置 | 方法 | 路径 |
内部存储 | Context.getFilesDir() | /data/data/<package name>/files/… |
外部存储(私有) | Context.getExternalFilesDir(null) | /mnt/sdcard/Android/data/<package name>/files/ |
外部存储(自建) | Environment.getExternalStorageDirectory() | /mnt/sdcard/ (自建目录) |
注:缓存一般放在私有外部存储
3.读写操作
//写文件
private static final String FILENAME = "log.txt";
public static void writeLog(String str){
File file = new File(LOG_PATH, FILENAME);
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
byte[] bt = new byte[1024];
bt = str.getBytes();
try {
FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(bt, 0, bt.length);
fos.close();
Log.i(TAG, "write log success");
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//读文件
public String readFileSdcardFile(String fileName){
String res="";
try{
FileInputStream fin =new FileInputStream(fileName);
intlength = fin.available();
byte[] buffer = newbyte[length];
fin.read(buffer);
res = EncodingUtils.getString(buffer,"UTF-8");
fin.close();
}catch(Exception e){
e.printStackTrace();
}
return res;
}
4.将assets中的
压缩文件
copy到Android/data下
if (!checkMapDir()) { // app加载(或splash)时调用
copyAssets(); // 将文件复制到系统缓存区
unpackMaps(); // 解压文件
}
private Boolean checkMapDir() {
File mapDir = new File(getExternalFilesDir(null), "name");
return mapDir.exists() && mapDir.isDirectory();
}
private void copyAssets() {
AssetManager assetManager = getAssets();
try {
InputStream in;
OutputStream out;
in = assetManager.open("name.zip");
File outFile = new File(getExternalFilesDir(null), "name.zip");
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
private void unpackMaps() {
File extDir = getExternalFilesDir(null);
if (extDir == null) {
return;
}
Unpacker unpacker = new Unpacker(extDir.getPath() + "/name.zip", extDir.getPath() + "/");
unpacker.unzip();
}
public void unzip() { // 解压方法
try {
FileInputStream fin = new FileInputStream(zip); // zip loc 为构造方法参数(String型)
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v(TAG, "Unzipping " + ze.getName());
if (ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(loc + ze.getName());
byte[] buffer = new byte[4096];
for (int c = zin.read(buffer); c != -1; c = zin.read(buffer)) {
fout.write(buffer, 0, c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "unzip", e);
}