Loading

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;
    }
}

 

posted @ 2018-02-15 10:15  stono  阅读(3361)  评论(0编辑  收藏  举报