栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android实现文件操作

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android实现文件操作

一、文件读取 1. 使用BufferedReader类         (1)BufferedReader类介绍
https://blog.csdn.net/ai_bao_zi/article/details/81134801
       (2)实现文件读取
    //读取指定目录下所有TXT文件的文件内容
    private String getFileContent(File file) {
        String content = "";
        if(!file.isDirectory()) {//判断该路径名的文件是否是一个目录(文件夹)
            if(file.getName().endsWith("txt")) {//判断是否是文本文件
                try {
                    InputStream inputStream = new FileInputStream(file);
                    if (inputStream != null) {
                        InputStreamReader inputReader = new InputStreamReader(inputStream, "UTF-8");
                        BufferedReader bufferedReader = new BufferedReader(inputReader);
                        String line = "";
                        //分行读取
                        while ((line = bufferedReader.readLine()) != null) {
                            content += line + "n";
                        }
                        inputStream.close();//关闭输入流
                    }
                }catch (java.io.FileNotFoundException e) {
                    Log.d("getFileContent: ", "The File doesn't exist");
                } catch (IOException e) {
                    Log.d("getFileContent", e.getMessage());
                }
            }
        }
        return content;
    }
二、文件写入 1. 使用RandomAccessFile类          (1)RandomAccess类介绍
https://www.cnblogs.com/lijianli/p/9680265.html
         (2)实现文件写入
    //将字符串写入文本文件中(makeFilePath函数及配套使用的函数见文章后面的“附录”)
    private void writeTxtToFile(String contentstr, String filePath, String fileName) {
        //生成文件夹之后,再生成文件,不然会出错
        makeFilePath(filePath, fileName);

        String filePathStr = filePath + fileName;
        //每次写入时,都换行写
        String contentStr = contentstr + "rn";
        try {
            File file = new File(filePathStr);
            if (!file.exists()) {
                Log.d("writeTxtToFile", "create the file; " + filePathStr);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(contentStr.getBytes());
            ToastUtil.showLong("写入成功!");
            Log.d("writeTxtToFile","写入成功");
            raf.close();
        } catch (Exception e) {
            Log.e("writeFIleToFile", "Error on write File: " + e);
        }
    }

 

三、文件修改 1. 使用FileWriter类         (1)FileWriter类介绍
菜鸟教程:https://www.runoob.com/java/java-filewriter.html
        (2)实现文件修改
    //修改数据(以读取文件的编辑框中的内容覆盖原文件内容)
    //makeFilePath函数及配套使用的函数见文章后面的“附录”
    private void modifyFile() {
        String contentStr = readFileEt.getText().toString();
        //生成文件夹之后,再生成文件,不然会出错
        makeFilePath(filePath, fileName);

        String filePathStr = filePath + fileName;
        try {
            File file = new File(filePathStr);
            if (!file.exists()) {
                Log.d("modifyFile", "create the file: " + filePathStr);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file);
            fw.write(contentStr);
            ToastUtil.showLong("修改成功!");
            Log.d("modifyFile","修改成功");
            fw.close();
        } catch (Exception e) {
            Log.e("modifyFile", "Error on Write File: " + e);
        }
    }

四、文件复制 1. 使用FileInputStream和FileOutputStream类
    //复制文件
    public boolean copyFile(String filePathFrom, String filePathTo) {
        File fileFrom = new File(filePathFrom);
        File fileTo = new File(filePathTo);
        if(!fileFrom.exists()) {
            fileFrom.mkdir();
            Log.d("FileMoveAsyncTask: ", "copyFile: " + "文件fileFrom不存在,重新创建!");
        }
        if(!fileTo.exists()) {
            fileTo.mkdir();
            Log.d("FileMOveAsyncTask: ", "copyFile: " + "文件fileTo不存在,重新创建!");
        }
        boolean isCopySuc = false;
        File fileFrom2 = new File(filePathFrom + "data.txt");
        File fileTo2 = new File(filePathTo + "data.txt");
        try {
            InputStream is = new FileInputStream(fileFrom2);
            FileOutputStream fos = new FileOutputStream(fileTo2);

            byte[] buffer = new byte[1024];
            int byteCount = 0;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            fos.close();
            is.close();
            isCopySuc = true;
            Log.d("FileMoveAsyncTask", "copyFile: " + "文件复制成功");
        }catch (java.io.FileNotFoundException e) {
            Log.d("FileMoveAsyncTask: ", fileTo2.toString());
            Log.d("FileMoveAsyncTask: ", "The FileTo doesn't exist");
        } catch (IOException e) {
            Log.d("FileMoveAsyncTask", "copyFile" + e.getMessage());
        }
        return isCopySuc;
    }
 五、附录 1. makeFilePath函数及配套函数
    //生成文件
    private File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    //生成文件夹
    private static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                Log.d("makeRootDirectory", "mkdir:" + file.toString());
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/273698.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号