文件java替换字符 [英] Files java replacing characters

查看:90
本文介绍了文件java替换字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须检查一个文本文件是否存在,然后我必须替换一个字母,说一个到o。我已经做了第一部分如何取代char

  class FDExists {
public static void main(String args [] ){
File file = new File(trial.java);
布尔exists = file.exists();
if(!exists){

System.out.println(您搜索的文件或目录不存在:+ exists);
$ b} else {

System.out.println(你正在搜索的文件或目录确实存在:+ exists);





这个我已经完成了你不能在一行代码中做到这一点。



你有(使用InputStream)读取文件,修改内容并将其写入文件中(使用OutputStream)。

示例代码。为了更好地理解算法,我省略了try / catch / finally块,但是在真实的代码中,您必须添加具有正确资源释放的块。你也可以用系统分隔符替换\\\
,并用参数替换a和o。

$ p $ public void replaceInFile(File file)throws IOException {

File tempFile = File.createTempFile(buffer,.tmp);
FileWriter fw = new FileWriter(tempFile);

阅读器fr =新的FileReader(文件);
BufferedReader br = new BufferedReader(fr); (br.ready()){
fw.write(br.readLine()。replaceAll(a,o)+\\\
);

while
}

fw.close();
br.close();
fr.close();

//最后替换原始文件。
tempFile.renameTo(file);
}


I have to check a text doc whether it exists or not and then i have to replace a letter in that say a to o. I have done the first part how to replace 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);
    }
  }
}

This i have done

解决方案

You cannot do that in one line of code.

You have to read the file (with an InputStream), modify the content, and write it in the file (with an OutputStream).

Example code. I omitted try/catch/finally blocks for a better comprehension of the algorithm but in a real code, you have to add theses blocks with a correct gestion of resources liberation. You can also replace "\n" by the system line separator, and replace "a" and "o" by parameters.

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替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆