您的位置:首页 > 编程语言 > Java开发

ReplaceText

2014-05-03 22:24 330 查看


import java.io.*;

import java.util.*;

public class ReplaceText {

 public static void main(String[] args) throws FileNotFoundException {

  // Check command-line parameter usage

  if(args.length != 4) {

   System.out.println(

     "Usage: java ReplaceText sourceFile targetFile oldStr newStr");

   System.exit(0);

  }

  

  // Check if source file exists

  File sourceFile = new File(args[0]);

  if(!sourceFile.exists()) {

   System.out.println("Source file " + args[0] + " does not exists");

   System.exit(0);

  }

  

  // Check if targer file exists

  File targetFile = new File(args[1]);

  if(targetFile.exists()) {

   System.out.println("Target file " + args[1] + " already exists");

   System.exit(0); 

  }

  

  // Create a Scanner for input and PrintWriter for output

  Scanner input = new Scanner(sourceFile);

  PrintWriter output = new PrintWriter(targetFile);

  

  while(input.hasNext()) {

   String s1 = input.nextLine();

   String s2 = s1.replaceAll(args[2], args[3]);

   output.println(s2);

  }

  

  input.close();

  output.close();

 }

}

java ReplaceText sourcrFile targerFile oldString newString
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息