我已经编写了一个程序,该程序应该从现有文件中获取一个值,将该值添加到该值上,删除该文件,创建该文件的一个新实例,并将新的值写入该文件的新实例。
public static void main(String[] args) throws InterruptedException, IOException {
//initialize newFile and writer
File newFile = new File("C:\\Users\\boung\\Desktop\\python\\daysSince.txt");
FileWriter writer = new FileWriter("C:\\Users\\boung\\Desktop\\python\\daysSince.txt", true);
//if newFile doesn't exist or of newFile doesn't contain any content, create newFile and write "1" to newFile
if(newFile.length() == 0) {
System.out.println("empty");
writer.write("1");
writer.write("\r\n");
writer.close();
} else {
//get contents of newFile
StringBuilder contentBuilder01 = new StringBuilder();
try (Stream<String> stream = Files.lines( Paths.get("C:\\Users\\boung\\Desktop\\python\\daysSince.txt"), StandardCharsets.UTF_8)) {
stream.forEach(s -> contentBuilder01.append(s).append("\n"));
} catch (IOException e) {
e.printStackTrace();
}
//convert content to integer
String content = contentBuilder01.toString();
content = content.replaceAll("\\D+", "");
int value = Integer.parseInt(content);
System.out.println(value);
//add 1 to the value that was returned from getting the contents of newFile and assign it to newValue
int newValue = value + 1;
//delete newFile
newFile.delete();
//create new instance of newFile to prepare for next execution
if(newFile.length() == 0) {
newFile = new File("C:\\Users\\boung\\Desktop\\python\\daysSince.txt");
}
FileWriter writer1 = new FileWriter("C:\\Users\\boung\\Desktop\\python\\daysSince.txt", true);
//write newValue to new instance of newFile
writer1.write(newValue);
System.out.println("printed " + newValue);
writer1.write("\r\n");
writer1.close();
}
} 问题发生在此区域。
writer1.write(newValue);
System.out.println("printed " + newValue);
writer1.write("\r\n");
writer1.close();假设newFile不存在,在运行该程序两次之后,预期的输出将如下所示
2
但这是我得到的输出
1
但在这里,如果文件为空或不存在,则程序可以将1写入文件
System.out.println("empty");
writer.write("1");
writer.write("\r\n");
writer.close();我想我在程序的逻辑上犯了一个错误,有谁能帮助我吗?
发布于 2020-06-10 06:48:01
我认为你的程序有两个问题:
因为writer仍处于打开状态,所以
newFile.delete();不执行任何操作。您需要首先通过执行writer.close();.writer1.write(newValue); writes newValue as an int来关闭writer。这意味着它直接获取表示该数字的所有二进制数,并将它们直接写入文件。相反,您希望将newValue编写为String,这将以文本形式生成该数字,以便您可以阅读它。因此,您希望使用writer1.write(Integer.toString(newValue));。发布于 2020-06-10 07:01:34
newFile.delete();是不必要的,您不需要删除该文件即可再次写入。下面的代码示例适用于我,并且输出正确。
StringBuilder contentBuilder01 = new StringBuilder();
try (Stream<String> stream = Files.lines( Paths.get(fileName), StandardCharsets.UTF_8)) {
stream.forEach(s -> contentBuilder01.append(s).append("\n"));
} catch (IOException e) {
e.printStackTrace();
}
FileWriter writer = new FileWriter(fileName);
writer.write(Integer.toString(Integer.parseInt(contentBuilder01.toString().trim()) + 1));
writer.close();https://stackoverflow.com/questions/62292787
复制相似问题