简体   繁体   中英

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:

  • Account number
  • Last Name
  • First Name
  • Balance (there would be no blanks but this site wouldn't let me)

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:

  • Use one file per entry. You'll have a directory with a lot of files, but the hard work of rewriting changed files and indexing by file name would be done by the os.
  • Use a fixed field width format. Define the width of each field then skip to the data you want. You could access your data like a big array.
  • Use a predetermined format with readily available tools for parsing and manipulation. XML and CSV come to mind

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM