简体   繁体   中英

Replace Line in .txt File based off of Flag

this question is different from the usual "I need to replace a line of code" questions, at least I hope.

I'm looking to edit a line of code in a text file called accounts.txt, and instead of using that line as the flag for the replacement, I need to use the line above it, since the progression of the file goes "Account Number, Balance". Any help is appreciated! Here's what I have so far.

public boolean modifyBalance(int accountNum, int newBalance) {
    try {
      FileReader fileReader = new FileReader("accounts.txt");
      BufferedReader file = new BufferedReader(fileReader);
      String line;
      String input = "";
      String flag;
      boolean foundFlag = false;
      Integer intInstance = accountNum;
      flag = intInstance.toString();

      while ((line = file.readLine()) != null) {
        input += line;
        if (line.equals(flag)) {
          file.readLine();
          input += "\n" + newBalance;
          foundFlag = true;
        }//end if
      }//end while
      return foundFlag;
    } //end try
    catch (IOException e) {
       System.out.println("Input Failure in Modify Balance of Account"       
                           + " Repository.");
       System.exit(0);
       return false;
     }
       // look up inObj in the text file and change the associated 
      // balance to newBalance
   }

Here are some things to think about.

If the file is small, you could read the whole thing into an array of strings (have a look at the javadocs for the Java 7 Files class). Then you can walk the array forwards and backwards to make your change. Then write the modified file back out.

If the file is large you could read from the input and write to a temporary file a line at a time (but delay the output by a line so you can trigger off the input flag). Then delete the old input file and rename the temporary.

Here's one way to do it.

Process :

-Writes all the lines of the file to an ArrayList

-If you find the flag, then mark that line number

-If your line number is not -1 you found the account, then make the change to the ArrayList and write all the lines back to the file.

public boolean modifyBalance(int accountNum, int newBalance)
{
    int lineNumberOfAccount = -1;
    boolean foundFlag = false;
    BufferedReader file = null;

    List<String> fileLines = new ArrayList<String>();
    try
    {
        FileReader fileReader = new FileReader("accounts.txt");
        file = new BufferedReader(fileReader);
        String line;
        String input = "";
        String flag;

        Integer intInstance = accountNum;
        flag = intInstance.toString();

        int lineNumber = 0;

        while ((line = file.readLine()) != null)
        {
            fileLines.add(line);

            System.out.println(lineNumber + "] " + line);
            // input += line;
            if (line.equals(flag))
            {
                lineNumberOfAccount = lineNumber;
                foundFlag = true;
            } // end if

            lineNumber++;

        } // end while
    } // end try
    catch (IOException e)
    {
        System.out.println("Input Failure in Modify Balance of Account" + " Repository.");
        // don't exit here, you are returning false
        // System.exit(0);
        return false;
    }
    // Close the file handle here
    finally
    {
        if (file != null)
        {
            try
            {
                file.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    // look up inObj in the text file and change the associated
    // balance to newBalance

    System.out.println("lineNumberOfAccount: " + lineNumberOfAccount);

    // found the account
    if (lineNumberOfAccount != -1)
    {
        int nextLine = lineNumberOfAccount + 1;

        // remove the old balance
        fileLines.remove(nextLine);

        // add the new balance
        fileLines.add(nextLine, String.valueOf(newBalance));

        System.out.println(fileLines);

        // write all the lines back to the file
        File fout = new File("accounts.txt");
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        try
        {
            fos = new FileOutputStream(fout);

            bw = new BufferedWriter(new OutputStreamWriter(fos));

            for (int i = 0; i < fileLines.size(); i++)
            {
                bw.write(fileLines.get(i));
                bw.newLine();
            }
        }
        catch (IOException e)
        {
            System.out.println("Could not write to file");
            return false;
        }
        // Close the file handle here
        finally
        {
            if (bw != null)
            {
                try
                {
                    bw.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    return foundFlag;
}

Notes :

  • You need to make sure you are closing your file handles.
  • Ideally, you should break up this code into at least 2 methods. One method to find the line number and another that writes the file back if the account was found.
  • Careful when using System.exit() I commented this out in my code because you may not want to exit the program this way if you get an IOException . You can also throw the exception or wrap it in a RuntimeException and let the calling code deal with it.
  • You may want to consider having the newBalance variable be a double instead of an int

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