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.
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).
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:
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). So you call 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.