在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被删除时丢失,则可以自定义文件路径,如下所示:

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来进行文件的读写,具体代码如下:

1.文件写入:

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();
}
}

2.文件读取

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;
}
05-11 15:34
查看更多