当前位置: 代码迷 >> Java相关 >> java读取文本和参数列表,用参数列表给的值替换里面字符串解决方法
  详细解决方案

java读取文本和参数列表,用参数列表给的值替换里面字符串解决方法

热度:2699   发布时间:2013-02-25 21:45:36.0
java读取文本和参数列表,用参数列表给的值替换里面字符串
读入几段文本,和一个参数列表,把文本中出现的所有参数都替换成参数列表中的参数值后返回。文本中的参数以$$括起。需考虑文本和参数列表都很大的情况。
例如:
文本一
$Name1$ is a good person. He has three sons: $Name6$, $Name3$ and $Name5$. $Name3$ is an engineer.

参数列表
Name1 Tom
Name2 Peter
Name3 Simon
Name4 John
Name5 Jerry
Name6 Harry
...

返回:
Tom is a good person. He has three sons: Harry, Simon and Jerry. Simon is an engineer.

------解决方案--------------------------------------------------------
public class CSDNTest2 {
private HashMap<String, String> map = new HashMap<String, String>();
public CSDNTest2(){
map.put("Name1"," Tom");
map.put("Name2"," Peter");
map.put("Name3"," Simon");
map.put("Name4"," John");
map.put("Name5"," Jerry");
map.put("Name6"," Harry");

}
public String replace(String oldString){
ArrayList<String> list= new ArrayList<String>();
String[] sorts = oldString.split("#");
String returnString ="";
//sorts.length必为奇数至少是1
for(int i=0;i<sorts.length;i++){
System.out.println(sorts[i]);
//所有奇数项即为所需参数(自己可以验证出来)
if (i%2!=0) {
String newString = "";
newString = map.get(sorts[i]);
sorts[i] = newString;
}
returnString =returnString+""+sorts[i];
}
return returnString.substring(1);
}
public static void main(String[] args) {
CSDNTest2 csdnTest2 = new CSDNTest2();
String oldString = "#Name1# is a good person. He has three sons: " +
"#Name6#, #Name3# and #Name5#. #Name3# is an engineer.";
System.out.println(csdnTest2.replace(oldString));
}
}



//这是我能想出的最直接的方法了,望采纳
------解决方案--------------------------------------------------------
从文本提取一样的,读文本信息保存到Map难道不会做吗?
首先把参数文本信息保存到Map
然后一行一行遍历要替换的文件,遍历一行就替换一次,然后把替换后的结果保存到另一个文件
for example
Java code
//保存参数到MapMap<String, String> params = new HashMap<String, String>();Scanner sc = new Scanner(new FileInputStream("参数文本文件"));while (sc.hashNext()) {    String[] sa = sc.nextLine().split("\\s+");    if (sa.length==2) params.put(sa[0], sa[1]);}sc.close();//替换文本并保存结果sc = new Scanner(new FileInputStream("替换文本文件"));PrintStream ps = new PrintStream(new FileOutputStream("结果文本文件"));Pattern p = Pattern.compile("[$]([^$]*?)[$]");while (sc.hashNext()) {    Matcher m = p.matcher(sc.nextLine());    StringBuffer buf = new StringBuffer();    while (m.find()) { //查找并替换参数        m.appendReplacement(buf, params.get(m.group(1)));    }    buf.appendTail();    ps.println(buf); //替换结果写入结果文件}sc.close();ps.close();
  相关解决方案