在Andriod开发中,文件存储和Java的文件存储相似。但须要注意的是,为了防止产生碎片垃圾,在建立文件时,要尽可能使用系统给出的函数进行建立,这样当APP被卸载后,系统能够将这些文件统一删除掉。获取文件的方式主要有如下几种。数组
File file1 =this.getFilesDir();//获取当前程序默认的数据存储目录 Log.d("Jinx",file1.toString()); File file2 =this.getCacheDir(); //默认的缓存文件存储位置 Log.d("Jinx",file2.toString()); File file3=this.getDir("test",MODE_PRIVATE); //在存储目录下建立该文件 Log.d("Jinx",file3.toString()); File file4=this.getExternalFilesDir(Environment.DIRECTORY_MUSIC); //获取外部存储文件 Log.d("Jinx",file4.toString()); File file5=this.getExternalCacheDir(); //获取外部缓存文件 Log.d("Jinx",file5.toString());
相应的Log日志以下,根据日志,能够很清楚看到每种方法获取到的文件的区别:缓存
03-28 03:19:06.948 12690-12690/com.example.jinx.file D/Jinx: /data/user/0/com.example.jinx.file/files 03-28 03:19:06.948 12690-12690/com.example.jinx.file D/Jinx: /data/user/0/com.example.jinx.file/cache 03-28 03:19:06.948 12690-12690/com.example.jinx.file D/Jinx: /data/user/0/com.example.jinx.file/app_test 03-28 03:19:06.963 12690-12690/com.example.jinx.file D/Jinx: /storage/emulated/0/Android/data/com.example.jinx.file/files/Music 03-28 03:19:06.966 12690-12690/com.example.jinx.file D/Jinx: /storage/emulated/0/Android/data/com.example.jinx.file/cache
固然,若是有一些重要的文件,不想在APP被删除时丢失,则能够自定义文件路径,以下所示:app
File file=new File("/mmt/sdcard/test"); if(!file.exists()) { Toast.makeText(MainActivity.this,"good!",Toast.LENGTH_SHORT).show(); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } else { Toast.makeText(MainActivity.this,"good!",Toast.LENGTH_SHORT).show(); }
Android经过自带的FileInputStream和FileOutputStream来进行文件的读写,具体代码以下:函数
private void WriteText(String text) { try { FileOutputStream fos=openFileOutput("a.txt",MODE_APPEND); //获取FileOutputStream对象 fos.write(text.getBytes()); //写入字节 fos.close(); //关闭文件流 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
private String Read() { String text=null; try { FileInputStream fis=openFileInput("a.txt"); //获取FileInputStream对象 //ByteArrayOutputStream来存放获取到的数据信息 ByteArrayOutputStream baos=new ByteArrayOutputStream(); byte [] buffer=new byte[1024]; //建立byte数组,分屡次获取数据 int len=0; while ((len=fis.read(buffer))!=-1) //经过FileInputStream的read方法来读取信息 { baos.write(buffer,0,len); //ByteArrayOutputStream的write方法来写入读到的数据 } text=baos.toString(); fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return text; }