java file content modification

Everyone is familiar with reading and writing files, but what about modification? If you modify it according to the ordinary read and write stream, you can only read it all out, and after modifying it in the memory, write it all in, so when there are too many file contents, the performance is very low.

When I encountered this problem recently, I found that the RandomAccessFile class can just solve my problem. Not much nonsense. I will paste the code directly below and share it with you. If there is something wrong, please give me advice, thank you.

 

    /**
     * 修改文件内容
     * @param fileName
     * @param oldstr
     * @param newStr
     * @return
     */
    private static boolean modifyFileContent(String fileName, String oldstr, String newStr) {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(FILEPATH+"/"+fileName, "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;
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325677674&siteId=291194637