java 文件java替换字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3940997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Files java replacing characters
提问by Sumithra
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
我必须检查一个文本文档是否存在,然后我必须替换一个字母,比如 a 到 o。我已经完成了第一部分如何替换字符
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
这是我做过的
回答by Benoit Courtine
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).
您必须读取文件(使用 InputStream)、修改内容并将其写入文件(使用 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.
示例代码。为了更好地理解算法,我省略了 try/catch/finally 块,但在实际代码中,您必须添加这些块并正确释放资源。也可以用系统行分隔符替换“\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);
}