我的文本文件内容看起来像这样
Fluster的同义词:
*恐慌
*扰动
* disconcert
*混淆 ......
现在我希望将*替换为数字。这样的事情。
输出
Fluster的同义词:
1)恐慌
2)干扰
3)令人不安
4)混淆 ......
修改
Integer count = 1;
File input = new File("C:\\Sample.txt");
File output = new File("C:\\output.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
Writer writer =new FileWriter(output);
while((line=reader.readLine())!=null)
{
if(line.contains("*"))
{
line.replace("*",count.toString() );
writer.write(line);
count++;
}
else
{
writer.write(line);
}
}
这是我在发布问题之前尝试过的。但这似乎不起作用。 现在有人可以帮帮我..?
答案 0 :(得分:2)
你应该写一个JAVA程序。
这可能会让你开始(粗略代码):
BufferedReader br = new BufferedReader(new FileReader(file));
//start reading file line-by-line
while ((line = br.readLine()) != null) {
//replace * with whatever you want
// Use a counter to keep track of lines to give corresponding line number
String val = line.replace("*",counterVar.toString());
}
br.close();
再次使用BufferedWriter
回写文件,如果您愿意,请用PrintWriter
换行,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outputfile")));
答案 1 :(得分:0)
尝试这样的事情(未经测试的代码):
try{
List<String> lines = Files.readAllLines(fileName, Charset.defaultCharset());
for (int i = 0; i< lines.size(); i++) {
lines.set(i, lines[i].replace("*", String.valueOf(i)));
}
} catch (IOException e) {
e.printStackTrace();
}
...//Then save the file