书上有题看不懂要干什么的
附题:编写一个程序,删除文本文件中指定的字符串。程序读取源文件,生成一个不含指定字符串的文件。然后将新文件复制到源文件上,要求从命令行传递字符串和文件名,如下所示:
Java Exercise16_5 John Exercise16_5.txt
这条命令从 Exercise16_5.txt 中删除字符串John。。以上就是题目了,搞不懂要干什么。。哪位大师教教。附代码最好了。

解决方案 »

  1.   

    要求应该就是读取源文件,然后将源文件中凡是用户输入的字符串(例如当前是John)删除,新建的文件中不包含有用户需要删除的字符串。偶不懂命令行java,期待高手顶顶。
      

  2.   

    Java Exercise16_5 John Exercise16_5.txt 
    命令 类           参数1 参数2
      

  3.   


    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;import org.apache.commons.io.FileUtils;public class Exercise16_5 {
    public static void main(String[] args) throws IOException {
    //接收参数
    String str = args[0];
    String filename = args[1];
    //读文件
    @SuppressWarnings("unchecked")
    List<String> lines = FileUtils.readLines(new File(filename));
    //处理字符串
    List<String> newLines = new ArrayList<String>();
    for (String line : lines) {
    newLines.add(line.replace(str, ""));
    }
    //生成新文件
    FileUtils.writeLines(new File(filename + ".tmp"), newLines);
    //拷贝文件
    FileUtils.copyFile(new File(filename + ".tmp"), new File(filename));
    //删除临时文件
    FileUtils.deleteQuietly(new File(filename + ".tmp"));
    }
    }注:org.apache.commons.io.FileUtils是apache commons-io项目包里的类
      

  4.   

    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;public class Test {public static void main(String[] args) {
    if(args.length<2) throw new IllegalArgumentException();
    String search = args[0];
    String oldname = args[1];
    String newname = "new_"+oldname;
    BufferedReader br = null;
    BufferedWriter bw = null;
    String line = null;
    File oldfile = new File(oldname);
    File newfile = new File(newname);
    try {
    br = new BufferedReader(new InputStreamReader(new FileInputStream(oldfile)));
    bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newfile)));
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    }
    try {
    while((line = br.readLine())!=null){
    String change = line.replaceAll("(\\s+)"+search+"\\s+", "$1");
    bw.write(change);
    bw.newLine();
    bw.flush();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }finally{
    try {
    bw.close();
    br.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    oldfile.delete();
    newfile.renameTo(oldfile);
    System.out.println("修改文件完毕");
    }}