有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java替换行输入。基于关闭标志的txt文件

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

我想在一个名为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
   }

共 (2) 个答案

  1. # 1 楼答案

    这里有一些事情需要考虑

    如果文件很小,您可以将整个内容读入一个字符串数组(看看Java7文件类的javadocs)。然后你可以前后移动阵列来进行更改。然后把修改过的文件写出来

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

  2. # 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;
    }
    

    注释

    • 您需要确保正在关闭文件句柄
    • 理想情况下,应该将此代码分解为至少两种方法。一种方法用于查找行号,另一种方法用于在找到帐户时将文件写回
    • 在使用System.exit()时要小心,我在代码中注释了这一点,因为如果得到IOException,您可能不想以这种方式退出程序。您还可以抛出异常或将其包装在RuntimeException中,并让调用代码处理它 您可能想考虑^ {< CD6> }变量是^ {< CD7}},而不是^ {< CD8> }