android-File保存数据
从内部私有存储器读取数据。使得存储器为私有的方法是对
openFileOutput()
使用MODE_PRIVATE
。public void writeInternalStoragePrivate( String filename, byte[] content) { try { //MODE_PRIVATE creates/replaces a file and makes // it private to your application. Other modes: // MODE_WORLD_WRITEABLE // MODE_WORLD_READABLE // MODE_APPEND FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE); fos.write(content); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
上述方法方法保存文件到/data/data/<package name>/files目录中了
mode取值:
MODE_APPEND 私有(只有创建此文件的程序能够使用,其他应用程序不能访问),在原有内容基础上增加数据
MODE_PRIVATE 私有,每次打开文件都会覆盖原来的内容
MODE_WORLD_READABLE 可以被其他应用程序读取
MODE_WORLD_WRITEABLE 可以被其他应用程序写入
Activity还提供了getCacheDir()和getFilesDir()方法:
getCacheDir()方法用于获取/data/data/<package name>/cache目录
getFilesDir()方法用于获取/data/data/<package name>/files目录
读取数据
/** * Reads a file from internal storage * @param filename the file to read from * @return the file content */ public byte[] readInternalStoragePrivate(String filename) { int len = 1024; byte[] buffer = new byte[len]; try { FileInputStream fis = openFileInput(filename); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int nrb = fis.read(buffer, 0, len); // read up to len bytes while (nrb != -1) { baos.write(buffer, 0, nrb); nrb = fis.read(buffer, 0, len); } buffer = baos.toByteArray(); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer; }
public void writeToExternalStoragePublic(String filename, InputStream input) { if (isExternalStorageAvailable() && !isExternalStorageReadOnly()) { try { File file = new File(path, filename); file.mkdirs(); FileOutputStream ouput = new FileOutputStream(file); byte buffer [] = new byte[4 * 1024]; int temp ; while((temp = input.read(buffer)) != -1){ output.write(buffer,0,temp); } output.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
从外存读取
public byte[] readExternallStoragePublic(String filename) { int len = 1024; byte[] buffer = new byte[len]; if (!isExternalStorageReadOnly()) { try { File file = new File(path, filename); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int nrb = fis.read(buffer, 0, len); //read up to len bytes while (nrb != -1) { baos.write(buffer, 0, nrb); nrb = fis.read(buffer, 0, len); } buffer = baos.toByteArray(); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return buffer; }