所以我有只有这一个.txt文件的内容:如何从文本文件中获取数字,而忽略前面的单词?
pizza 4
bowling 2
sleepover 1
我想要做的是,例如在第一线,忽略了“比萨”的一部分,但保存为4一个整数。
这是我迄今为止的一小段代码。
public static void addToNumber() {
PrintWriter writer;
Int pizzaVotes, bowlingVotes, sleepOverVotes;
try {
writer = new PrintWriter(new FileWriter("TotalValue.txt"));
}
catch (IOException error) {
return;
}
// something like if (stringFound)
// ignore it, skip to after the space, then put the number
// into a variable of type int
// for the first line the int could be called pizzaVotes
// pizzaVotes++;
// then replace the number 4 in the txt file with pizzaVote's value
// which is now 5.
// writer.print(pizzaVotes); but this just overwrites the whole file.
// All this will also be done for the other two lines, with bowlingVotes
// and sleepoverVotes.
writer.close();
} // end of method
我是初学者。正如你可以看到我的实际功能代码很短,我不知道继续。如果有人愿意指点我的方向,即使你只是给我一个网站的链接,这将是非常有益的...
编辑:我愚蠢以为PrintWriter可以读取文件
'PrintWriter'只用于*写* - 它不读*。 –
您必须首先**读取**数据,**将它们存储在适当的数据结构中,**处理**它们,然后将它们**写回到文件中。我建议你写最后写入文件的部分。 – Ingo
在创建读取数据的代码之后,您可以使用“正则表达式”来获取数字,但这会让您遇到另一个问题:如果某一行有多个数字,例如'比萨4保龄球5'... –