java - 如何使用 java FIle i/o 替换、删除或更新文件中的行

标签 java file file-io collections java-io

以下是我的 java 类文件:

Public class subscriberAction {
private Service1 s1 = ServiceFactory.getServiceImpl1();
private Service2 s2 = ServiceFactory.getServiceImpl2();
----
----
----

public Service1 getServiceImpl1Obj(){
    -----
    ----
    return s1.getInstance();
}

public Service2 getServiceImpl2Obj(){
    -----
    ----
    return s2.getInstance();
}

}//类(class)结束

我想通过动态使用java代码来删除私有(private)类变量并修改返回语句,如下代码所示。如果我运行编程的java文件,SubscriberAction java文件应该像这样修改。

Public class SubscriberAction {

public Service1 getServiceImpl1Obj(){
    -----
    ----
    return ServiceFactory.getServiceImpl1().getInstance();
}

public Service2 getServiceImpl2Obj(){
    -----
    ----
    return ServiceFactory.getServiceImpl2().getInstance();
}

}

你能帮我写一下java代码吗?

最佳答案

您不能直接在您的文件上执行此操作。以下是实现它的方法:

  1. Read your original file line by line
  2. If there is no modification required for the line, copy it to a backup/temp file
  3. If line change is required, write the updated line to the backup/temp file. If line is not required, don't write it to the backup/temp file.
  4. Once reading the original and writing to the backup/temp is finished, delete the original file
  5. Rename the backup/temp as original file

我希望你能编写同样的代码!

关于java - 如何使用 java FIle i/o 替换、删除或更新文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16769672/

相关文章:

java - 当检测到类扩展了 Enum 时,如何调用其 valueOf() 方法?

java - Spring 表达语言的映射

Python 在一次 write() 后关闭文件

java - 如何在java中按日期对目录中的文件进行排序?

file - JSONP 文件的正确扩展名是什么?

java - 使用 JFileChooser 保存字符串

java - 如何解决 SSL illegal_parameter?

java - 没有 StackTrace 的 Java 中的 NullPointerException

C 创建txt文件并附加当前日期和时间作为名称