![](/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.