![](/img/trans.png)
[英]Cannot write a text in a text file using FileWriter and Printwriter
[英]Cannot get PrintWriter to replace text in file
我正在尝试完成一个简单的程序,该程序使用命令行替换文件中的指定字符串。 命令行输入将为Java ReplaceText textToReplace filename文件代码已完成,但文件未替换指定的字符串。 我在Google上也遇到过类似情况,但是我无法弄清楚为什么我的代码无法正常工作。
import java.io.*;
import java.util.*;
public class ReplaceText{
public static void main(String[] args)throws IOException{
if(args.length != 2){
System.out.println("Incorrect format. Use java ClassName textToReplace filename");
System.exit(1);
}
File source = new File(args[1]);
if(!source.exists()){
System.out.println("Source file " + args[1] + " does not exist.");
System.exit(2);
}
File temp = new File("temp.txt");
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
while(input.hasNext()){
String s1 = input.nextLine();
String s2 = s1.replace(args[0], "a");
output.println(s2);
}
temp.renameTo(source);
source.delete();
}
}
}
编辑:编辑了代码,所以我不能同时读写文件,但是仍然无法正常工作。
通常,您不能替换字符串文件。 您需要逐行读取输入,必要时替换每一行,并将每一行写入一个新文件。 然后删除旧文件并重命名新文件。
首先,您的逻辑存在问题。 您正在重命名临时文件,然后立即将其删除。 首先删除旧文件,然后重命名临时文件。
另一个问题是您试图在try
块中执行删除和重命名:
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
...
temp.renameTo(source);
source.delete();
}
在try
块结束之前,流不会自动关闭。 流打开时,您将无法重命名或删除。 delete
和renameTo
返回一个布尔值,以指示它们是否成功,因此请谨慎检查这些值。
正确的代码可能类似于:
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
while(...)
{
...
}
}
// Try block finished, resources now auto-closed
if (!source.delete())
{
throw new RuntimeException("Couldn't delete file!");
}
if (!temp.renameTo(source))
{
throw new RuntimeException("Couldn't rename file!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.