zoukankan      html  css  js  c++  java
  • Java修改文件内容

    Java修改文件内容

    学习了:https://www.cnblogs.com/XiaoyangBoke/p/7468268.html

    进行了文件内容的修改:

    package com.stono.thread2;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    
    public class ModifyPackage {
    
    
        public static void main(String[] args) {
            String path = "D:\Java\gitworkspace\Coding\src\com\stono\thread2";
            File root = new File(path);
            File[] listFiles = root.listFiles();
            for (File file : listFiles) {
                boolean isDirectory = file.isDirectory();
                String name = file.getName();
                String substring = name.substring(4);
                if(isDirectory && name.length() == 7) {
                    int parseInt = Integer.parseInt(substring);
                    if(parseInt<100) {
                        System.out.println(parseInt);
                        File[] listFiles2 = file.listFiles(); // 找到里面的文件了;
                        for (File file2 : listFiles2) {
                            String oldstr="com.stono.thread2.page";
                            String newStr="com.stono.thread2.page0";
                            modifyFileContent(file2,oldstr,newStr);
                        }
                    }
                    
                }
            }
        }
    
        private static boolean modifyFileContent(File file2, String oldstr, String newStr) {
            RandomAccessFile raf = null;
            try {
                raf = new RandomAccessFile(file2, "rw");
                String line = null;
                long lastPoint = 0; //记住上一次的偏移量
                while ((line = raf.readLine()) != null) {
                    final long ponit = raf.getFilePointer();
                    if(line.contains(oldstr)){
                          String str=line.replace(oldstr, newStr);
                    raf.seek(lastPoint);
                    raf.writeBytes(str);
                    }
                    lastPoint = ponit; 
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
    }
  • 相关阅读:
    Linux学习之网络基础
    C# 随笔
    最牛B的编码套路
    c++ Primer 第七章不熟悉知识点总结
    oracle求表的倒数二行数据
    c++ Primer 第六章不熟悉知识点总结
    c++ Primer 第五章不熟悉知识点总结
    c++ Primer 第四章不熟悉知识点总结
    c++ Primer 第三章不熟悉知识点总结
    骑驴找马
  • 原文地址:https://www.cnblogs.com/stono/p/8449285.html
Copyright © 2011-2022 走看看