【问题标题】:Replace Line in .txt File based off of Flag根据标志替换 .txt 文件中的行
【发布时间】:2016-09-04 17:44:43
【问题描述】:

至少我希望这个问题不同于通常的“我需要替换一行代码”问题。

我正在寻找在名为 accounts.txt 的文本文件中编辑一行代码,而不是使用该行作为替换的标志,我需要使用它上面的行,因为文件的进展转到“帐号,余额”。任何帮助表示赞赏!这是我目前所拥有的。

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
   }

【问题讨论】:

  • 您的代码不会替换任何东西;它只读取。这个问题实际上是关于创建一个在找到帐户时返回true 的方法吗?
  • 尽管如此,您的问题只是关于寻找线路吗?
  • 我没有写代码行来重写文件。我想搜索文本文件并将新行追加到它应该在的位置,但我从未放入方法的写入部分。

标签: java file text bufferedreader overwrite


【解决方案1】:

这里有一些事情要考虑。

如果文件很小,您可以将整个内容读入字符串数组(查看 Java 7 Files 类的 javadocs)。然后,您可以前后移动阵列以进行更改。然后将修改后的文件写回。

如果文件很大,您可以从输入中读取并一次将一行写入临时文件(但将输出延迟一行,以便您可以触发输入标志)。然后删除旧的输入文件并重命名临时文件。

【讨论】:

    【解决方案2】:

    这是一种方法。

    流程

    -将文件的所有行写入ArrayList

    -如果找到标志,则标记该行号

    -如果您的行号不是-1,则您找到了帐户,然后将更改为ArrayList并将所有行写回文件。

    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;
    }
    

    注意事项

    • 您需要确保关闭文件句柄。
    • 理想情况下,您应该将此代码分解为至少 2 个方法。一种查找行号的方法,另一种在找到帐户时将文件写回的方法。
    • 使用System.exit() 时要小心 我在代码中注释掉了这一点,因为如果您收到IOException,您可能不想以这种方式退出程序。您也可以抛出异常或将其包装在 RuntimeException 中,让调用代码处理它。
    • 您可能需要考虑将newBalance 变量设为double 而不是int

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多