Android 文件读写最全解析

本文目录

  • Android文件读写概述
  • 读取raw目录文件
  • 读取assets目录文件
  • data/data/(包名) 目录文件读写
    • 写数据
    • 读数据
  • sdcard文件读写
    • 申请动态权限
    • 写数据
    • 读数据
    • sdcard文件读写完整代码

推荐阅读:
Android 通过HttpURLConnection访问Http协议网络
Android SQlite数据库使用详解
Android xUtils框架最全使用详解
Android 动态权限最全解析

Android文件读写概述

Android 文件读写最全解析_第1张图片
在Androi中文件读写一共有以下目录

  • raw目录
  • asserts目录
  • data/data/包名
  • sdcard目录

其中raw下的和asserts下的文件可以以资源文件的形式读取,这些目录的数据只能读取,不能写入,两者目录下的文件在打包后会原封不动的保存在apk包中,不会被编译成二进制。
data/data/包名sdcard目录文件可读可写。其中data/data/包名目录不需要申请权限,sdcard目录需要申请权限

读取raw目录文件

Android工程默认是没有raw文件夹的在读文件前我们先把raw 文件夹以及文件建好

  • 点中工程的res目录 右键New -> Directory -> 弹窗中输入raw
  • 点中刚刚新建的raw目录 右键New -> File -> 弹窗中输入test.txt
  • 点开刚刚新建的test.txt文件 ,往里面输入hello world
    Android 文件读写最全解析_第2张图片
    读数据方法
   InputStream inputStream = null;
   Reader reader = null;
    BufferedReader bufferedReader = null;
    try {
        //得到资源中的Raw数据流
        inputStream = getResources().openRawResource(R.raw.test);
        reader = new InputStreamReader(inputStream);// 字符流
        bufferedReader = new BufferedReader(reader); //缓冲流
        StringBuilder result = new StringBuilder();
        String temp;
        while ((temp = bufferedReader.readLine()) != null) {
            result.append(temp);
        }
        Log.i("MainActivity", "result:" + result);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

从打印的结果中我们可以看出数据读取成功
在这里插入图片描述

读取assets目录文件

Android工程默认是没有assets文件夹的,在读文件前我们先把assets 文件夹以及文件建好

  • 点中工程 右键New -> Folder -> Assets Folder
  • 点中刚刚新建的Assets Folde目录 右键New -> File -> 弹窗中输入test.txt
  • 点开刚刚新建的test.txt文件 ,往里面输入hello world

  • 读去assets文件中的数据方法
		InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {
            //得到资源中的asset数据流
            inputStream = getResources().getAssets().open("test.txt");
            reader = new InputStreamReader(inputStream);// 字符流
            bufferedReader = new BufferedReader(reader); //缓冲流
            StringBuilder result = new StringBuilder();
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                result.append(temp);
            }
            Log.i("MainActivity", "result:" + result);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

从打印的结果中我们可以看出数据读取成功
在这里插入图片描述

data/data/(包名) 目录文件读写

将数据以普通文件的形式保存在 /data/data/包名中,该方法不需要申请权限。
存放在数据区(/data/data/包名)的文件可以使用openFileOutputopenFileInput进行操作。
也可以直接指定文件/data/data/包名路径读写。

该目录存放文件类型规则如下:

路径 功能
data/data/包名/shared_prefs 存放SharedPreferences数据
data/data/包名/databases 存放数据库数据
data/data/包名/files 存放普通数据
data/data/包名/cache 存放缓存文件

写数据

方法1:openFileOutput

        FileOutputStream fileOutputStream = null;
        try {
            String text = "hello world";
            fileOutputStream = openFileOutput("test.txt", MODE_PRIVATE);
            fileOutputStream.write(text.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

openFileOutput方法参数详解

	@Override
    public FileOutputStream openFileOutput(String name, int mode)
        throws FileNotFoundException {
        
    }
  • name 存储文件名字
  • mode 存储方式 其值的含义如下
参数值 参数含义
Context.MODE_PRIVATE 指定该文件数据只能被本应用程序读、写
Context.MODE_WORLD_READABLE 指定该文件数据能被其他应用程序读,但不能写
Context.MODE_WORLD_WRITEABLE 指定该文件数据能被其他应用程序读
Context.MODE_APPEND 该模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件;

方法2:传统方法读写

   String text = "hello world";
   File file1=new File("/data/data/com.lucashu.file/","test.txt");
      FileOutputStream fileOutputStream = null;
     try {
         fileOutputStream = new FileOutputStream(file1);
         fileOutputStream.write(text.getBytes());
     } catch (Exception e) {
         e.printStackTrace();
     }finally {
         if (fileOutputStream != null) {
             try {
                 fileOutputStream.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
     }

执行以后我们可以看到添加了一个文件
Android 文件读写最全解析_第3张图片

读数据

方法1:openFileInput

		FileInputStream fileInputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {
            fileInputStream = openFileInput("test.txt");
            reader = new InputStreamReader(fileInputStream);// 字符流
            bufferedReader = new BufferedReader(reader); //缓冲流
            StringBuilder result = new StringBuilder();
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                result.append(temp);
            }
            Log.i("MainActivity", "result:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

方法2:openFileInput

		InputStream inputStream = null;
        Reader reader = null;
        BufferedReader bufferedReader = null;
        try {

            File file=new File("/data/data/com.lucashu.file/", "test.txt");
            inputStream = new FileInputStream(file);
            reader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(reader);
            StringBuilder result = new StringBuilder();
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                result.append(temp);
            }
            Log.i("MainActivity", "result:" + result);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

从打印的结果中我们可以看出数据读取成功

在这里插入图片描述
我们也可以用一下方法来获取改文件的路径

getFilesDir();// data/data/包名/files 目录
getFilesDir().getParent(),;// data/data/包名/ 目录

sdcard文件读写

sdcard读写的数据将数据保存在 /mnt/sdcard目录,该目录读写需要先申请动态权限,动态权限申请方法如下

申请动态权限

Android 动态权限最全解析
Android 文件读写最全解析_第4张图片

首先需要在manifest.xml中添加权限


 
 

如果是AndroidQ 或者更高的版本还需要在manifest.xml文件中的application节点下加入
android:requestLegacyExternalStorage="true"
申请动态权限方法:

private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};

private void checkPermission() {
//检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                .WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(this, "请开通相关权限,否则无法正常使用本应用!", Toast.LENGTH_SHORT).show();
        }
        //申请权限
        ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);

    } else {
        Toast.makeText(this, "已授权成功!", Toast.LENGTH_SHORT).show();
        writeSdcard();

    }
}

Activity中动态权限的回调方法

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_EXTERNAL_STORAGE: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "授权成功!", Toast.LENGTH_SHORT).show();
                writeSdcard();
            } else {
                Toast.makeText(this, "授权被拒绝!", Toast.LENGTH_SHORT).show();


            }
            return;
        }

    }
}

写数据

private void writeSdcard()  {
        String text = "hello world";
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File storage = Environment.getExternalStorageDirectory();
                File tmepfile = new File(storage.getPath());
                if (! tmepfile.exists()) {
                    tmepfile.mkdirs();
                }
                File file1=new File(tmepfile,"test.txt");
                if (!file1.exists()){
                    try {
                        file1.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(file1);
                    fileOutputStream.write(text.getBytes());
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if (fileOutputStream != null) {
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

执行以后我们可以看到添加了一个文件
Android 文件读写最全解析_第5张图片

读数据

private void readSdcard() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                InputStream inputStream = null;
                Reader reader = null;
                BufferedReader bufferedReader = null;
                try {
                    File storage = Environment.getExternalStorageDirectory();
                    File tmepfile = new File(storage.getPath());
                    File file=new File(tmepfile, "test.txt");
                    inputStream = new FileInputStream(file);
                    reader = new InputStreamReader(inputStream);
                    bufferedReader = new BufferedReader(reader);
                    StringBuilder result = new StringBuilder();
                    String temp;
                    while ((temp = bufferedReader.readLine()) != null) {
                        result.append(temp);
                    }
                    Log.i("MainActivity", "result:" + result);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (bufferedReader != null) {
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }
    }

在这里插入图片描述

sdcard文件读写完整代码

package com.lucashu.file;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission();
    }


    private void writeSdcard()  {
        String text = "hello world";
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File storage = Environment.getExternalStorageDirectory();
                File tmepfile = new File(storage.getPath());
                if (! tmepfile.exists()) {
                    tmepfile.mkdirs();
                }
                File file1=new File(tmepfile,"test.txt");
                if (!file1.exists()){
                    try {
                        file1.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(file1);
                    fileOutputStream.write(text.getBytes());
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if (fileOutputStream != null) {
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }


    private void readSdcard() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                InputStream inputStream = null;
                Reader reader = null;
                BufferedReader bufferedReader = null;
                try {
                    File storage = Environment.getExternalStorageDirectory();
                    File tmepfile = new File(storage.getPath());
                    File file=new File(tmepfile, "test.txt");
                    inputStream = new FileInputStream(file);
                    reader = new InputStreamReader(inputStream);
                    bufferedReader = new BufferedReader(reader);
                    StringBuilder result = new StringBuilder();
                    String temp;
                    while ((temp = bufferedReader.readLine()) != null) {
                        result.append(temp);
                    }
                    Log.i("MainActivity", "result:" + result);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (bufferedReader != null) {
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }
    }
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};

    private void checkPermission() {
        //检查权限(NEED_PERMISSION)是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请开通相关权限,否则无法正常使用本应用!", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);

        } else {
            Toast.makeText(this, "已授权成功!", Toast.LENGTH_SHORT).show();
            readSdcard();

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "授权成功!", Toast.LENGTH_SHORT).show();
                    readSdcard();
                } else {
                    Toast.makeText(this, "授权被拒绝!", Toast.LENGTH_SHORT).show();

                }
                return;
            }

        }
    }

}

作者:lucashu
出处:https://blog.csdn.net/huweiliyi/category_8913738.html
原创不易,欢迎转载,但未经作者同意请保留此段声明,并在文章页面明显位置给出原文链接。

你可能感兴趣的:(Android,#,Android基础)