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
}
# 1 楼答案
这里有一些事情需要考虑
如果文件很小,您可以将整个内容读入一个字符串数组(看看Java7文件类的javadocs)。然后你可以前后移动阵列来进行更改。然后把修改过的文件写出来
如果文件很大,您可以从输入中读取数据,然后一次一行地向临时文件写入数据(但要将输出延迟一行,以便触发输入标志)。然后删除旧的输入文件并重命名临时文件
# 2 楼答案
这里有一个方法
过程:
-将文件的所有行写入
ArrayList
-如果你找到了旗子,那就标记行号
-如果您的行号不是-1,您找到了帐户,那么对
ArrayList
进行更改,并将所有行写回文件注释:
System.exit()
时要小心,我在代码中注释了这一点,因为如果得到IOException
,您可能不想以这种方式退出程序。您还可以抛出异常或将其包装在RuntimeException
中,并让调用代码处理它李>