【发布时间】:2020-09-29 05:33:42
【问题描述】:
我编写了一个程序,它应该从现有文件中获取一个值,向该值添加一个,删除文件,创建文件的新实例,并将新值写入文件的新实例.
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();
我认为我在程序的逻辑上犯了一个错误,有人可以帮忙吗?
【问题讨论】:
标签: java filewriter file-writing