使用相同的尝试资源读取和写入文件
我正在使用Java,并且有一种方法可以替换configfile
中参数的值。我使用try-with-resources,以便两者都会自动关闭。但是,我遇到了出乎意料的行为 - 而
循环不会从该文件中读取任何内容,因为在Java进入try-with-with-resources块之后,configfile
变为空。
private static boolean replaceValue(String param, String newValue) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(configFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(configFile))) {
String line;
StringBuilder sb = new StringBuilder();
boolean isParamPresent = false;
while ((line = br.readLine()) != null) {
if (line.startsWith(param + configDelimiter)) {
line = line.replaceAll("(?<==).*", newValue);
isParamPresent = true;
}
sb.append(line);
sb.append("\n");
}
if (isParamPresent) {
bw.write(sb.toString());
return true;
}
}
return false;
}
如果我更改为下面的代码,则可以按预期工作。
if (isParamPresent) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(configFile))) {
bw.write(sb.toString());
return true;
}
我不明白什么原因configfile
变得空。有人可以解释怎么了吗?
I'm using Java, and I have a method that replaces a value of a parameter in configFile
. I use try-with-resources so that both will be closed automatically. However, I encounter an unexpected behavior - the while
loop doesn't read anything from that file because immediately after Java enters the try-with-resources block, configFile
becomes empty.
private static boolean replaceValue(String param, String newValue) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(configFile));
BufferedWriter bw = new BufferedWriter(new FileWriter(configFile))) {
String line;
StringBuilder sb = new StringBuilder();
boolean isParamPresent = false;
while ((line = br.readLine()) != null) {
if (line.startsWith(param + configDelimiter)) {
line = line.replaceAll("(?<==).*", newValue);
isParamPresent = true;
}
sb.append(line);
sb.append("\n");
}
if (isParamPresent) {
bw.write(sb.toString());
return true;
}
}
return false;
}
If I change to code to be like this below, it works as expected.
if (isParamPresent) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(configFile))) {
bw.write(sb.toString());
return true;
}
I don't understand what causes configFile
to become empty. Can someone explain what's wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
filewriter(String fileName)
constructor调用fileOutputstream(字符串名称)
将Append
flag设置为false。这意味着该文件将不会在附录模式下打开。根据我在Windows上的测试,如果未设置附录标志,则立即清除文件。因此,在您的第一个变体中,自清除以来没有什么可阅读的。您的第二个变体在将内容读取到
stringBuffer
中时已清除。The
FileWriter(String fileName)
constructor callsFileOutputStream(String name)
which sets theappend
flag to false. This means the file will not be opened in append mode.Based on my testing on windows the file is immediately cleared if the append flag is not set. So in your first variant there's nothing to read, since it was cleared. Your second variant works as it's cleared after you've read the content into your
StringBuffer
.