题目是:替换源文件中的文本并将修改存储到新的文件中,将修改存储到原文件中。例如,调用
java ReplaceText 1.txt oldString newString(用newString替换源文件中的oldString)我写的如下,但每次修改之后用StringBuffer 获取的修改之后的文本内容再写到原文件中后,就把源文本清空了。请大侠们帮我看看怎么做啊。谢谢了import java.io.*;
import java.util.*;public class ReplaceText {
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.out.println("Usage: java ReplaceText sourceFile oldString newString");
System.exit(0);
} File sourceFile = new File(args[0]);
if (!sourceFile.exists()) {
System.out.println("Source file " + args[0] + " does not exist");
System.exit(0);
} Scanner input = new Scanner(sourceFile);
PrintWriter output = new PrintWriter(sourceFile);
while (input.hasNext()) {
String s1 = input.nextLine();
String s2 = s1.replaceAll(args[1], args[2]);
StringBuffer temp=new StringBuffer();
        temp.append(s2);
output.println(temp.toString());
} input.close();
output.close();
}
}
比如我的文本为“1.txt”内容为“john is a man”,调用java ReplaceText 1.txt john hj 这样使得“1.txt”的内容变成“hj is a man”

解决方案 »

  1.   

     StringBuffer temp=new StringBuffer();
    放在while前面
      

  2.   

    这样改下:import java.io.File;
    import java.io.PrintWriter;
    import java.util.Scanner;public class ReplaceText {
        public static void main(String[] args) throws Exception {
         args=new String[]{"d:/aaa.txt","h","b"};
            if (args.length != 3) {
                System.out.println("Usage: java ReplaceText sourceFile oldString newString");
                System.exit(0);
            }        File sourceFile = new File(args[0]);
            if (!sourceFile.exists()) {
                System.out.println("Source file " + args[0] + " does not exist");
                System.exit(0);
            }
            File dFile=File.createTempFile("ReplaceText",null,sourceFile.getAbsoluteFile().getParentFile());        Scanner input = new Scanner(sourceFile);
            PrintWriter output = new PrintWriter(dFile);
            
            while (input.hasNext()) {
                String s1 = input.nextLine();
                String s2 = s1.replaceAll(args[1], args[2]);
                StringBuffer temp=new StringBuffer();
                temp.append(s2);
                output.println(temp.toString());
            }        input.close();
            output.close();
            sourceFile.delete();
            dFile.renameTo(sourceFile);
        }
    }
      

  3.   

    上面请把  args=new String[]{"d:/aaa.txt","h","b"}; 注释掉
      

  4.   

    你这个是先删除源文件 再新建同名的修改之后的文档吧 ?可不可以不用删除直接用toString获取文档中的内容之后,直接重写里面的内容吗?
      

  5.   

    在循环中:
    String s1 = input.nextLine();//读取
    output.println(temp.toString());//写入,覆盖掉了源文件,下一个周期:
    String s1 = input.nextLine();//读不到了,文件已经被覆盖