我的工作是用Hound替换所有出现的Bond。我已经尝试了以下代码。
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class myTry {
public static void main(String[] args)
{
String fileName = "C:\\Users\\KingKong\\Desktop\\WorkSpace\\Victory\\src\\test2.txt";
FileReader f = null;
StringTokenizer str = null;
String temp = "";
try {
f = new FileReader(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(f);
try {
temp = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
str = new StringTokenizer(temp);
String token = "";
System.out.println(str);
while(str.hasMoreTokens())
{
token = str.nextToken();
if(token.equals("Bond"))
{
token.replace("Bond","Hound");
}
}
String newMod = str.toString();
System.out.println(newMod);
System.out.println(str);
}
}
但它通过打印语句为我提供了输出(通过控制台):
java.util.StringTokenizer@4d24bd93
java.util.StringTokenizer@4d24bd93
java.util.StringTokenizer@4d24bd93
这是什么意思?我的逻辑是 - 访问文件, - 将数据读入字符串标记器对象, - 逐个检查令牌中是否有任何“债券”, - 如果是,请更改它。
感谢@kgdesouz 的格式化此外,我放弃了使用字符串标记器的想法。我想做的是由普通的字符串类完成。这里是下面的代码
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class myTry {
public static void main(String[] args)
{
String fileName = "C:\\Users\\KingKong\\Desktop\\WorkSpace\\Victory\\src\\test2.txt";
FileReader f = null;
StringTokenizer str = null;
String temp = "";
try {
f = new FileReader(fileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(f);
try {
temp = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(temp);
String newMod = temp.replaceAll("Bond","Hound");
System.out.println(newMod);
}
}
它给出了输出
Bond is a bad boy.Bond goes to temple EveryDay.
Hound is a bad boy.Hound goes to temple EveryDay.
干杯!!