RandomAccessFile-递归操作指定文件夹下的所有文件内容

递归操作指定文件夹下的所有文件内容

    public static void toFiles(File rootFile) {
        if(rootFile == null){
            return;
        }
        if(rootFile.isDirectory()){
            File[] listFiles = rootFile.listFiles();
            for(File file:listFiles) {
                if(file.isFile()) {
                    toFile(file);
                }else {
                    toFiles(file);
                }
            }
        }else{
            toFile(rootFile);
        }
    }

    public static void toFile(File file){
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "rw");
            String line = null;
            long lastPoint = 0; //记住上一次的偏移量
            while ((line = raf.readLine()) != null) {
                final long ponit = raf.getFilePointer();
                String lineStr = new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                String replaceLine = "*****想要针对lineStr 处理的逻辑写在此处即可****";
                raf.seek(lastPoint);
                raf.write(replaceLine.getBytes(StandardCharsets.UTF_8));
                lastPoint = ponit;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
发布了148 篇原创文章 · 获赞 159 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/qq_33594101/article/details/103085277