android 文件操作工具类FileUtils

将字符串写入到文本文件中覆盖写入

 public static void coverWriteTxtToFile(String strcontent, String strFilePath){
        //生成文件夹之后,再生成文件,不然会出错
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }

            //重写文件,覆盖掉原来的数据
            FileOutputStream out = new FileOutputStream(file);
            out.write(strcontent.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            Log.e("File", "Error on write File:" + e);
            e.printStackTrace();
        }
    }

追加写入

 public static void methoAdd(String strcontent, String filePath, String fileName) {
        FileWriter fw = null;
        try {
            String strFilePath = filePath + fileName;
//如果文件存在,则追加内容;如果文件不存在,则创建文件
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("File", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
            }
            fw = new FileWriter(file, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter pw = new PrintWriter(fw);
        pw.println(strcontent);
        pw.flush();
        try {
            fw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

读取指定目录下的TXT文件的文件内容

    public static String getFileContent(File file) {
        String content = "";
        if (!file.isDirectory()) {  //检查此路径名的文件是否是一个目录(文件夹)
            if (file.getName().endsWith("txt") || file.getName().endsWith("gson")){//文件格式为""文件
                try {
                    InputStream instream = new FileInputStream(file);
                    if (instream != null) {
                        InputStreamReader inputreader
                                = new InputStreamReader(instream, "UTF-8");
                        BufferedReader buffreader = new BufferedReader(inputreader);
                        String line = "";
                        //分行读取
                        while ((line = buffreader.readLine()) != null) {
                            content += line + "\n";
                        }
                        instream.close();//关闭输入流
                    }
                } catch (FileNotFoundException e) {
                    Log.d("File", "The File doesn't not exist.");
                } catch (IOException e) {
                    Log.d("File", e.getMessage());
                }
            }
        }
        return content;
    }

复制整个文件夹或者具体文件到另一个目录下

  /**
     * 复制单个文件
     */
    public static boolean copyFile(String oldPathName, String newPathName) {
        try {
            File oldFile = new File(oldPathName);
            if (!oldFile.exists() || !oldFile.isFile() || !oldFile.canRead()) {
                return false;
            }
            FileInputStream fileInputStream = new FileInputStream(oldPathName);
            FileOutputStream fileOutputStream = new FileOutputStream(newPathName);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = fileInputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            fileInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 复制文件夹及其中的文件
     */
    public boolean copyFolder(String oldPath, String newPath) {
        try {
            File newFile = new File(newPath);
            if (!newFile.exists()) {
                if (!newFile.mkdirs()) {
                    return false;
                }
            }
            File oldFile = new File(oldPath);
            String[] files = oldFile.list();
            File temp;
            for (String file : files) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file);
                } else {
                    temp = new File(oldPath + File.separator + file);
                }

                if (temp.isDirectory()) {   //如果是子文件夹
                    copyFolder(oldPath + "/" + file, newPath + "/" + file);
                } else if (!temp.exists()) {
                    return false;
                } else if (!temp.isFile()) {
                    return false;
                } else if (!temp.canRead()) {
                    return false;
                } else {
                    FileInputStream fileInputStream = new FileInputStream(temp);
                    FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
                    byte[] buffer = new byte[1024];
                    int byteRead;
                    while ((byteRead = fileInputStream.read(buffer)) != -1) {
                        fileOutputStream.write(buffer, 0, byteRead);
                    }
                    fileInputStream.close();
                    fileOutputStream.flush();
                    fileOutputStream.close();
				}
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

读取Assets目录下文件内容

   public static String getFromAssets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String result = "";
            while ((line = bufReader.readLine()) != null){
                result += line;
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

删除文件夹中除了fileName命名的其他文件

  public static void deleteToFileName(File file, String fileName) {
        try {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (files.length>1){
                    for (int i = 0; i < files.length; i++) {
                        if (files[i].getName().contains(fileName)) {
                        } else {
                            files[i].delete();
                        }
                    }
                }
                //  file.delete();//如要保留文件夹,只删除文件,请注释这行
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

清除应用数据

  /**
     * 清除应用数据
     *  context.getFilesDir().getAbsolutePath() + File.separator;
     * DataCleanManager.DeleteFile(newFile("data/data/"+getPackageName()));
     */
    public static void clearAppData(Context context){
        try {
            String path="data/data/"+context.getPackageName();
            File file=new File(path);
            if (file.exists()){
                deleteDir(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

清除应用缓存数据

  public static void clearAllCache(Context context) {
        try {
            deleteDir(context.getCacheDir());
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                deleteDir(context.getExternalCacheDir());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

删除文件夹

    private static boolean deleteDir(File dir) {
        if (dir != null) {
            if (dir.isDirectory()) {
                String[] children = dir.list();
                if (children != null) {
                    for (String child : children) {
                        deleteDir(new File(dir, child));
                    }
                }
            } else {
                return dir.delete();
            }
        }
        return false;
    }

获取存储文件路径

  public static String getLogFile(Context context) {
        String path ;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        // SD卡目录
            path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "file/";
        } else {// 如果SD卡不存在,就保存到本应用的目录下
            path = context.getFilesDir().getAbsolutePath() + File.separator + "file/";
        }
        return path ;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值