编辑文件中的特定字符串?



所以我正在创建一个程序,该程序在调用时将具有输入,转到文件并更改分配给调用字符串的数字。例如:

该文件如下所示:

stone 0 wood 5 water 2 metal 5

如果调用"wood",它将进入文件,找到 wood,然后将 add one 发送到 wood 右侧的值,这只会将该值更改为 6,然后保存文件。

我在互联网上环顾四周,但找不到很多针对我的特定问题量身定制的内容。它要么将 int 更改为一个或另一个,要么将所有 int 更改为某些东西。

public class Main { 
public static void main(String[] args) {
FileWriter fw;
BufferedReader reader;
StringBuffer ib;
String allBlockAndNull = "stone 0 wood 5 water 2 metal 5";
String strDir = "C:\Users\amdro\Desktop\test.txt";
File fileDir = new File(strDir);
//creates file it doesn't exist
try {
fw = new FileWriter(fileDir);
fw.write(allBlockAndNull);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}finally {}
}
}

如果您可以从上面扩展,那就太好了!

这是针对您的问题的一个非常简单基本的解决方案:它包括读取文件,将所有更改附加到字符串并用字符串覆盖同一文件。

创建扫描程序以读取文本文件并初始化新的字符串变量

Scanner s = new Scanner(new File("fileName.txt"));
String line = "";

当文本文件中仍有字符时,获取wordnumber

while(sc.hasNext()){
String word = s.next();
int number = s.nextInt();

然后,在while循环中,使用switchcase检查单词。例如,如果 word = "wood",则附加"wood"和新数字,newNumberline

case "wood":
line += word + " " + newNumber + " ";
break;

默认值将附加单词和旧数字,number

default:
line += word + " " + number + " ";

最后,只需创建一个FileWriter和一个BufferedWriter即可将line写入文本文件。

您不能将数字添加到文件中的值,因为所有值都是字符串,但您可以做的是替换字符串值

public static void main(String[] args) throws IOException {
File file = new File("file.txt");//The file containing stone 0 wood 5 water 2 metal 5
BufferedReader reader = new BufferedReader(new FileReader(file));
String words = "", list = "";
while ((words = reader.readLine()) != null) {
list += words;
}
reader.close();
Scanner s = new Scanner(file);
if(list.contains("wood")) {
String replacedtext = list.replaceAll("wood 5", "wood 6");
FileWriter writer = new FileWriter("file.txt");
writer.write(replacedtext);
writer.close();
}
}
}

最新更新