[英]Replacing a line of text in Java
I have an ATM and I need to open a text file that contains the account info in the following format: 我有一个自动柜员机,我需要打开一个文本文件,其中包含以下格式的帐户信息:
The file name is Accountnfomation.txt. 文件名为Accountnfomation.txt。
Basically, I need to be able to replace/change the Balance value depending on what the user wants. 基本上,我需要能够根据用户需要替换/更改“余额”值。 I know how to find the account number in the text file, but I don't know how to skip the next two lines and edit it.
我知道如何在文本文件中找到帐号,但是我不知道如何跳过接下来的两行并进行编辑。 Here is some code I've written:
这是我编写的一些代码:
try {
Scanner Account= new Scanner(new File ("AccountInformation.txt"));
FileOutputStream Account2= new FileOutputStream ("AccountInformation.txt",true);
while (Account.hasNextLine()) {
String nextToken = Account.next();
if (nextToken.equalsIgnoreCase(MyLoginID)) { //searches for specific match
// the idea here would to be to edit balance amount
}
}
}
This is what I have so far. 到目前为止,这就是我所拥有的。 It finds the account number, but I don't know what to do next.
它会找到帐号,但是我不知道下一步该怎么做。
In your problem, it would be nice to get to the line you want to change, change it, and leave everything else the same. 在您遇到的问题中,最好先更改,更改并保持其他所有内容不变。 Unfortunately a file isn't a collection of lines, it is a collection of bytes.
不幸的是,文件不是行的集合,而是字节的集合。 If you want to change "10" to "1000" you need to insert some new bytes, that means everything behind it needs to move down a few bytes (likely four or so, assuming utf8).
如果要将“ 10”更改为“ 1000”,则需要插入一些新的字节,这意味着其后面的所有内容都需要向下移动几个字节(假设为utf8,则大概为四个左右)。
In the real world we get around this by not storing data in flat files. 在现实世界中,我们通过不将数据存储在平面文件中来解决此问题。 Assuming you still want a really simple, file based, human readable, format:
假设您仍然想要一种非常简单的,基于文件的,人类可读的格式:
Using nio: 使用nio:
Path path = FileSystems.getDefault().getPath(filePath);
try {
List<String> lines = Files.readAllLines(path);
} catch (IOException e) {
e.printStackTrace();
}
So according to your format balance would be index 3 (without any empty lines). 因此,根据您的格式余额,索引为3(没有任何空行)。 So you call
lines.set(3, newBalance);
因此,您调用
lines.set(3, newBalance);
, loop through the lines again, adding them to another StringBuilder
and store the content in a file using the toString()
method of the StringBuilder
. ,再次遍历这些行,将它们添加到另一个
StringBuilder
然后使用StringBuilder
的toString()
方法将内容存储在文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.