Android 文件的读取和写入

(1)openFileInput和openFileOutput的使用

文件的使用,注意最后要用finally给关闭掉。

openFileOutput:(写入文件,如果没有文件名可以创建,这里不需要判断是否有这个文件)---> FileOutputStream
openFileInput:(读取文件,没有文件名会保存,debug的时候会看到,不影响ui)---> FileInputStream

    保存文件:(FileOutputStream 保存地址;data/data/包名/files/, 下面是写入的四种模式)
    MODE_APPEND:即向文件尾写入数据
    MODE_PRIVATE:即仅打开文件可写入数据
    MODE_WORLD_READABLE:所有程序均可读该文件数据
    MODE_WORLD_WRITABLE:即所有程序均可写入数据。

    private void savePackageFile() {
        String msg = tvSaveMessage.getText().toString() + " 
";
        FileOutputStream outputStream;

        try {
            outputStream = openFileOutput(filename, Context.MODE_APPEND);
            outputStream.write(msg.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    读取文件:(FileInputStream 读取包名下files文件夹下的文件)
    private void readSaveFile() {
        FileInputStream inputStream;

        try {
            inputStream = openFileInput(filename);
            byte temp[] = new byte[1024];
            StringBuilder sb = new StringBuilder("");
            int len = 0;
            while ((len = inputStream.read(temp)) > 0){
                sb.append(new String(temp, 0, len));
            }
            Log.d("msg", "readSaveFile: 
" + sb.toString());
            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    文件的初始化:(创建需要的文件)
    File logFile = new File(context.getFilesDir(), MainActivity.filename);
    // Make sure log file is exists
    if (!logFile.exists()) {
        boolean result; // 文件是否创建成功
        try {
            result = logFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        if (!result) {
            return;
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

(2)BufferReader和BufferWriter使用:

保存文件:如果没有会自动创建,如果有的话会覆盖。 当在创建时加入true参数,回实现对文件的续写。 false则会覆盖前面的数据
public static void bufferSave(String msg) {
    try {
        BufferedWriter bfw = new BufferedWriter(new FileWriter(logFile, true));
        bfw.write(msg);
        bfw.newLine();
        bfw.flush();
        bfw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

读取文件:这里需要做判断,如果没有这个文件会报错。
public static void bufferRead() {
    try {
        BufferedReader bfr = new BufferedReader(new FileReader(logFile));
        String line = bfr.readLine();
        StringBuilder sb = new StringBuilder();
        while (line != null) {
            sb.append(line);
            sb.append("
");
            line = bfr.readLine();
        }
        bfr.close();

        Log.d("buffer", "bufferRead: " + sb.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

(3)SD卡读取和写入—路径:/storage/sdcard0/ 
SD卡权限;

<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

往SD卡写入文件的方法
public void savaFileToSD(String filename, String filecontent) throws Exception {
    //如果手机已插入sd卡,且app具有读写sd卡的权限
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
   filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;

        //这里就不要用openFileOutput了,那个是往手机内存中写数据的
        FileOutputStream output = new FileOutputStream(filename);
        output.write(filecontent.getBytes());
        //将String字符串以字节流的形式写入到输出流中
        output.close();
        //关闭输出流
    } else Toast.makeText(context, "SD卡不存在或者不可读写", Toast.LENGTH_SHORT).show();
}

//读取SD卡中文件的方法
//定义读取文件的方法:
public String readFromSD(String filename) throws IOException {
    StringBuilder sb = new StringBuilder("");
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
        //打开文件输入流
        FileInputStream input = new FileInputStream(filename);
        byte[] temp = new byte[1024];

        int len = 0;
        //读取文件内容:
        while ((len = input.read(temp)) > 0) {
            sb.append(new String(temp, 0, len));
        }
        //关闭输入流
        input.close();
    }
    return sb.toString();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

(4)读取raw和assets文件夹下的文件

res/raw:文件会被映射到R.java文件中,访问的时候直接通过资源ID即可访问,而且 他不能有目录结构,就是不能再创建文件夹
assets:不会映射到R.java文件中,通过AssetManager来访问,能有目录结构,即, 可以自行创建文件夹

读取文件资源;

raw: 
InputStream is =getResources().openRawResource(R.raw.filename);  

assets: 
AssetManager am =  getAssets();   
InputStream is = am.open("filename");

这里已经写完了,后续会持续更新文章...
原文地址:https://www.cnblogs.com/exmyth/p/8424843.html