我做了一些dcode,通过复制第一个文件并更换了正确的行来改变一行。然后删除第一个文件并重命名临时文件。这是代码:
File countFile = new File(DEF_PATH + DEF_PATH_EX);
File tempFile = new File(DEF_PATH + DEF_PATH_EX_TEMP);
PrintWriter pWriter = new PrintWriter(new BufferedWriter(new FileWriter(tempFile)));
BufferedReader bReader = new BufferedReader(new FileReader(countFile));
String lineRead;
boolean hasChanged = false;
while ((lineRead = bReader.readLine()) != null)
{
String[] dataLine = lineRead.split(":");
if (dataLine[0].equals(userString.substring(1)))
{
lineRead = String.format("%s:%s:", dataLine[0], Integer.toString(Integer.parseInt(dataLine[1]) + 1));
hasChanged = true;
System.out.println(lineRead);
}
pWriter.println(lineRead);
}
if (!hasChanged)
{
pWriter.println(userString.substring(1) + ":1:");
}
pWriter.close();
bReader.close();
countFile.delete();
tempFile.renameTo(new File(DEF_PATH + DEF_PATH_EX));
问题是我不能做“countFile.delete()”当我已经删除它1次之前。因此,重命名也是不行的。