AndroidStudio-3.2.1(十二)4种文件读写方式

本篇介绍android开发中4中文件读写方式。

  • 应用程序下的文件读写
  • assets下的文件读取
  • raw下的文件读取
  • SD卡下的文件读写
应用程序下的文件读写

在as里提供了DeviceFileExplorer查看应用程序的目录,具体路径是/data/data/应用程序包名。
如果是虚拟机可以直接看到该路径下的内容,如果是真机需要root。
androd对应用程序下的文件读写固定在files文件夹中,一般不需要权限。
在这里插入图片描述

  • 创建文件并写入内容:
   WriteSysFile(MainActivity.this,"appfile.txt");//调用函数
 //定义函数
 public void WriteSysFile(Context context, String filename) {
        try {
            FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);//openFileOutput函数会自动创建文件
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
            osw.write("随便插入点啥");
            osw.flush();
            fos.flush();  //输出缓冲区中所有的内容
            osw.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

函数调用后,我们可以DeviceFileExplorer中,看到程序路径下多了一个appfile.txt文件。

  • 读取文件
 public void ReadSysFile(Context context, String filename) {
        try {
            FileInputStream fis = context.openFileInput(filename);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            char[] input = new char[fis.available()];  //available()用于获取filename内容的长度,但是对中文有问题,建议使用BufferReader
            isr.read(input);  //读取并存储到input中
            isr.close();
            fis.close();//读取完成后关闭
            String str = new String(input); 
            System.out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

上述读写直接使用了系统给定的openFileOutput和openFileInput方法,其实也可以通过File类去操作,也是在files文件夹下创建。

 String path = getFilesDir().getPath();
 File file = new File(path + "/appfile.txt");
        if (!file.exists()) {
            file.createNewFile();
        } else {
            System.out.println("文件名:" + file.getName());
            System.out.println("路径:" + file.getAbsolutePath());
        }
assets下的文件读取

首先添加assets文件夹,在程序目录上右键.添加完成后assets文件夹是与res文件夹同级的。这里的文件最后会被打包到apk中,一般存放一些图片\html\js\ css 等文件,大小不能超过1M。也可以在此文件夹下建立文件目录。
在这里插入图片描述

 public void ReadAssetsFile(Context context, String file) {
        try {
            InputStream open = context.getResources().getAssets().open(file);
            InputStreamReader isr = new InputStreamReader(open, "UTF-8");
            BufferedReader bfr = new BufferedReader(isr);
            String ln;
            while ((ln = bfr.readLine()) != null) {
                System.out.println(ln);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
raw下的文件读取

首先添加raw文件夹,在res文件夹上右键添加。这里的文件最后会被打包到apk中,同时会被编译到R.java文件中,访问的时候直接使用资源ID。raw不可以有目录结构,大小没有限制,可以放音频、视频文件。
在这里插入图片描述

public void ReadRawFile(Context context, String file) {
        try {
            InputStream inputStream = context.getResources().openRawResource(R.raw.rf);
            InputStreamReader isr = null;
            isr = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bfr = new BufferedReader(isr);
            String ln;
            while ((ln = bfr.readLine()) != null) {
                System.out.println(ln);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
SD卡下的文件读写

如果用的是虚拟机,那么自动就有sd卡的挂载位置,具体路径为/mnt/sdcard/。可以在DeviceFileExplorer中查看。sd卡中数据的读写需要权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

在这里插入图片描述

  • 创建并写入文件
public void WriteSDFile(Context context,String filename) {
        try {
            File sdPath = Environment.getExternalStorageDirectory();
            if (!sdPath.exists()) {
                Toast.makeText(context,"不存在SD卡目录",Toast.LENGTH_SHORT).show();
                return;
            }
            File myfile = new File(sdPath, filename);
            myfile.createNewFile();
            System.out.println("文件名:" + myfile.getName());
            System.out.println("路径:" + myfile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 读取sd卡文件
public void ReadSDFile(Context context,String filename) {
        try {
            File sdPath = Environment.getExternalStorageDirectory();
            if (!sdPath.exists()) {
                Toast.makeText(context,"不存在SD卡目录",Toast.LENGTH_SHORT).show();
                return;
            }
            File myfile = new File(sdPath, filename);
            FileInputStream fis = new FileInputStream(myfile);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader bfr = new BufferedReader(isr);
            String ln;
            while ((ln = bfr.readLine()) != null) {
                System.out.println(ln);
            }
            isr.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • 7
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值