我必须检查文本文档是否存在,然后我必须将 a 中的字母替换为 o。我已经完成了如何替换 char 的第一部分
class FDExists{
public static void main(String args[]){
File file=new File("trial.java");
boolean exists = file.exists();
if (!exists) {
System.out.println("the file or directory you are searching does not exist : " + exists);
}else{
System.out.println("the file or directory you are searching does exist : " + exists);
}
}
}
我已经做到了
最佳答案
您无法通过一行代码完成此操作。
您必须读取文件(使用输入流),修改内容,然后将其写入文件(使用输出流)。
示例代码。为了更好地理解算法,我省略了 try/catch/finally block ,但在实际代码中,您必须通过正确的资源释放管理来添加这些 block 。您还可以将“\n”替换为系统行分隔符,将“a”和“o”替换为参数。
public void replaceInFile(File file) throws IOException {
File tempFile = File.createTempFile("buffer", ".tmp");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while(br.ready()) {
fw.write(br.readLine().replaceAll("a", "o") + "\n");
}
fw.close();
br.close();
fr.close();
// Finally replace the original file.
tempFile.renameTo(file);
}
关于java - 文件java替换字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3940997/