Android之文件读写
16lz
2021-01-23
一、基本概念
在Android应用中保存文件,保存的位置有两处
①手机自带的存储空间,较小(如200M),适合保存一些小文件,Android中保存位置在data/data/应用包名/files目录
②外存储设备如SD卡,较大,适合保存大文件如视频,Android中保存位置在mnt/sdcard目录,保存在sdcard目录
保存的位置通过android的file explorer视图可以找到
二、例子
/** * 文件操作类 * * @author XY * */public class FileService{/** * 上下文对象 */private Context context;public FileService(Context context){super();this.context = context;}/** * 保存文件至手机自带的存储空间 * * @param filename 文件名 * @param fileContent 文件内容 */@SuppressWarnings("static-access")public void save(String filename, String fileContent) throws Exception{FileOutputStream fos = context.openFileOutput(filename, context.MODE_PRIVATE); // 默认保存在手机自带的存储空间fos.write(fileContent.getBytes("UTF-8"));fos.close();}/** * 保存文件至SD卡 * * @param filename 文件名 * @param fileContent 文件内容 */public void saveInSDCard(String filename, String fileContent) throws Exception{// 若文件被保存在SDCard中,该文件不受读写控制File file = new File(Environment.getExternalStorageDirectory(), filename);FileOutputStream fos = new FileOutputStream(file);fos.write(fileContent.getBytes("UTF-8"));fos.close();}/** * 读取文件内容 * * @param filename 文件名 * @return */public String read(String filename) throws Exception{FileInputStream fis = context.openFileInput(filename); // 默认到手机自带的存储空间去找ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;// 将内容读到buffer中,读到末尾为-1while ((len = fis.read(buffer)) != -1){// 本例子将每次读到字节数组(buffer变量)内容写到内存缓冲区中,起到保存每次内容的作用outStream.write(buffer, 0, len);}// 取内存中保存的数据byte[] data = outStream.toByteArray();fis.close();String result = new String(data, "UTF-8");return result;}}MainActivity
try{// 存储在手机自带存储空间fs.save(filename, fileContent);Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_SHORT).show();// 存储在外部设备SD卡// 判断SDCARD是否存在和是否可读写if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){fs.saveInSDCard(filename, fileContent);Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_SHORT).show();}else{Toast.makeText(getApplicationContext(), R.string.failsdcard, Toast.LENGTH_SHORT).show();}}catch (Exception e){Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_SHORT).show();Log.e(tag, e.getMessage());}
文件名不带路径,直接输入如xy.txt
对于SD卡的操作,需要在AndroidManifest.xml加入权限
<!-- 在SDCard中创建和删除文件的权限 --><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /><!-- 往SDCard中写入数据的权限 --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
三、一些API
①Environment.getExternalStorageDirectory()获取的路径为mnt/sdcard目录
②Activity中提供了两个API
getCacheDir()获取的路径为data/data/应用包名/cache目录
getFilesDir()获取的路径为data/data/应用包名/files目录
更多相关文章
- 【转】Android中对Log日志文件的分析
- android:gravity 和 android:layout_Gravity属性——android开发
- Android 文件格式
- android项目中每个文件的作用
- Fast File Transfer – 让 Android 通过 WIFI 传输文件到任何无
- Android开发5——文件读写
- Android布局文件属性笔记
- adb设备连接以及文件拷贝