Android 文件读写和文件夹创建和删除总结

来源:互联网 发布:centos git 备份 编辑:程序博客网 时间:2024/05/29 09:16

转载请标明出处:http://blog.csdn.net/htwhtw123/article/details/72493301
谷歌的官网讲解:保存文件
这里提供Android 文件操作,具体内容有:
1.写文件,存于任意路径:
2.读文件,读任意路径
3.用openFileOutput写文件,写于data/data/app的包名/files文件夹下
4.用openFileInput读文件,读data/data/app的包名/files文件夹下文件
5.创建文件夹
6.删除文件夹及其下文件及文件夹
7.字节方式读写文件(支持音频文件读写和视频文件读写,且速度较快)
8.SharedPreferences 存储与文件删除
9.读写外部存储设备

注意:在非应用目录文件路径读写文件或者读写外置内存目录文件时,需要赋予APP读写删的权限;应用目录文件路径获取:getFilesDir()(只有本应用有读写权限)

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

如果运行在Android 6.0及其以上的设备,请在读写非应用内部路径的内存前,写下动态申请内存读写权限的代码:

//请求应用内存读写权限    public void requestPower() {        if (ContextCompat.checkSelfPermission(this,                Manifest.permission.WRITE_EXTERNAL_STORAGE)                != PackageManager.PERMISSION_GRANTED) {            if (ActivityCompat.shouldShowRequestPermissionRationale(this,                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {            } else {                ActivityCompat.requestPermissions(this,                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,                                Manifest.permission.READ_EXTERNAL_STORAGE}, 1);            }        }    }

1.写文件,存于任意路径:

需要申请权限

(1)以覆盖方式写文件:
//path为文件保存路径包含文件名,msg为需要写入的内容

 public static void writeFile(String path, String msg) {        FileOutputStream outStream;        File file =new File(path);        try {            outStream = new FileOutputStream(file);        } catch (FileNotFoundException e) {            return;        }        try {            outStream.write(msg.getBytes());        } catch (Exception e) {        } finally {            try {                outStream.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }

(2)追加方式写文件:
//path为文件路径(包含文件名)

public  void writeFileAppend(String path, String conent) {    BufferedWriter out = null;    try {        out = new BufferedWriter(new OutputStreamWriter(                new FileOutputStream(new File(path), true)));        out.write(conent);    } catch (Exception e) {        e.printStackTrace();    } finally {        try {            out.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

2.读文件,读任意路径

需要申请权限

//path为文件路径(包含文件名),方法返回值为读取文件内容

 static String read(String path){        String result = "";        BufferedReader br = null;        try {             br = new BufferedReader(new FileReader(new File(path)));            String temp;            while ((temp= br.readLine())!=null)                result += temp;        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally {            if(br!=null)                try {                    br.close();                } catch (IOException e) {                    e.printStackTrace();                }        }        return result;    }

3.用openFileOutput写文件

写的文件位置:data/data/app的包名/files/自命名文件,不需要申请内存读写权限

openFileOutput和openFileInput读写模式
常量 含义
MODE_PRIVATE 默认模式,文件只可以被调用该方法的应用程序访问
MODE_APPEND 如果文件已存在就向该文件的末尾继续写入数据,而不是覆盖原来的数据。
MODE_WORLD_READABLE 赋予所有的应用程序对该文件读的权限。
MODE_WORLD_WRITEABLE 赋予所有的应用程序对该文件写的权限。
//以下为私有覆盖的方式写文件:

private void save(String fileName,String  data) {    FileOutputStream out=null;    BufferedWriter writer = null;    try {        out = openFileOutput(fileName, Context.MODE_PRIVATE);        writer = new BufferedWriter(new OutputStreamWriter(out));        writer.write(data);    } catch (IOException e) {        e.printStackTrace();    } finally {        try {            if (writer != null) {                writer.close();            }            if(out!=null){                out.close();            }        } catch (IOException e) {            e.printStackTrace();        }    }}

4.用openFileInput读文件

读data/data/app的包名/files/自命名文件,不需要申请读写内存的权限

private String read(String fileName) {    FileInputStream in = null;        BufferedReader reader = null;        StringBuilder content = new StringBuilder();        try {            in = openFileInput(fileName);            reader = new BufferedReader(new InputStreamReader(in));            String line = "";            while ((line = reader.readLine()) != null) {                content.append(line);            }        } catch (IOException e) {            e.printStackTrace();        } finally {            if (reader != null) {                try {                    reader.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return content.toString();}

5.创建文件夹

//在根路径下创建文件夹folder:

static  final String rootPath= Environment.getExternalStorageDirectory().getPath()+"/";File file=new File(rootPath+"folder");if(!file.exists()){    file.mkdir();}

6.删除文件夹及其下文件及文件夹:

public void deleteFolderFile(String filePath) {    if (!TextUtils.isEmpty(filePath)) {        try {            File file = new File(filePath);            if (file.isDirectory()) {                File files[] = file.listFiles();                for (int i = 0; i < files.length; i++) {                    deleteFolderFile(files[i].getAbsolutePath());                }            }            if (!file.isDirectory()) {                file.delete();            } else {/                if (file.listFiles().length == 0) {/                    file.delete();                }            }        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

注:当用户卸载应用时,Android 系统会删除以下各项:
1.保存在内部存储中的所有文件
2.使用 getExternalFilesDir() 保存在外部存储中的所有文件。

7.字节方式读写文件(支持音频和视频读写,且速度较快)

  //以追加的方式写文件    public static void writeFileAppend(String path, byte[]b) {        FileOutputStream fs = null;        BufferedOutputStream bos = null;        try {            fs = new FileOutputStream(new File(path), true);//这里改成false则为覆盖的方式写文件            bos = new BufferedOutputStream(fs);            bos.write(b);            bos.flush();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (fs != null)                    fs.close();            } catch (IOException e) {                e.printStackTrace();            }            try {                if (bos != null) {                    bos.close();                }            } catch (IOException e) {                e.printStackTrace();            }        }    }    //读文件    public static byte[] readFile(String path) {        int len= (int) new File(path).length();        byte b[] = new byte[len];        StringBuffer result=new StringBuffer();        BufferedInputStream bis = null;        FileInputStream fi = null;        try {            fi = new FileInputStream(new File(path));            bis = new BufferedInputStream(fi);            int temp;            int i=0;            while ((b[i] = (byte)bis.read()) != -1) {                i++;            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }finally {            if (bis != null) {                try {                    bis.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (fi != null) {                try {                    fi.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return b;    }

8. SharedPreferences 存储

以键值对方式存储,存储位置为:data/data/app的包名/shared_prefs/自命名文件.xml。不需要内存读写权限。

主要有两种模式可以选
MODE_PRIVATE: 只有当前的应用程序才可以对这个SharedPreferences文件进行读写
MODE_MULTI_PROCESS:多个应用对同一个 SharedPreferences文件进行读写

以下为MODE_PRIVATE情况的示例

(1)把数据存入SharedPreferences例子(存入到文件名为data.xml的文件中):

SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();editor.putString("name", "Tom");editor.putInt("age", 28);editor.putBoolean("married", false);editor.commit();

(2)取出SharedPreferences中的数据(将刚刚存的数据取出):

SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);String name = pref.getString("name", "");int age = pref.getInt("age", 0);boolean married = pref.getBoolean("married", false);

(3)清空SharedPreferences中的数据:

SharedPreferences sp = getSharedPreferences("data", Context.MODE_PRIVATE);        SharedPreferences.Editor editor = sp.edit();        editor.clear();        editor.commit();

注意:此处清空指不再有可以取出的数据,实际上data.xml依旧存在,并且依旧存在少量字符。

(4)彻底清除SharedPreferences的文件,其实就是使用一般的文件删除的方法就可以,依旧不需要内存读写权限。以下举例之前生成的删除data.xml。

String filePath="data/data/getPackageName().toString()/shared_prefs";File file = new File(filePath, "userData.xml");        if (file.exists()) {            file.delete();        }

9.读写外部存储设备

需要申请权限

检查外部存储设备是否可以读写:

public boolean isExternalStorageWritable() {    String state = Environment.getExternalStorageState();    if (Environment.MEDIA_MOUNTED.equals(state)) {        return true;    }    return false;}

外部存储文件分两种:
公共文件:
供其他应用和用户自由使用的文件。 当用户卸载应用时,用户应仍可以使用这些文件。
私有文件
属于您的应用且在用户卸载您的应用时应予删除的文件。(实际上其他应用也可以访问)

获取公共文件的相册文件夹对象:

File file=Environment.getExternalStoragePublicDirectory(            Environment.DIRECTORY_PICTURES);

获取外部存储上应用的专用目录的根目录:

 getExternalFilesDir(null) ;
原创粉丝点击