我正在使用 bufferedWriter 和 FileWriter 将记录器写入我的 java 程序(csv 格式)。
当我在程序运行时打开 csv 文件并继续写入该文件时,出现此异常:“该进程无法访问该文件,因为它正在被另一个进程使用”。
我想要的是,当我在程序运行时打开 csv 文件时,csv 文件将以读取模式打开,并且程序将成功写入该文件。
我通过将 bufferedWriter 和 FileWriter 的关闭更改为 .flush() 而不是 .close() 解决了这个问题
原始最小记录器代码(具有原始关闭功能)
public class logger {
private BufferedWriter bw = null;
private FileWriter fw = null;
private File file = null;
logger(String nclass) {
path = "c:\\test\\test.csv";
this.file = new File(path);
// Check if the file is already exist.
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
}
public void writeToFile(String msg) {
entryWrite();
try {
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
fw.append(msg);
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
exitWrite();
}
}
}
private void close() {
try {
if (bw != null) {
bw.close();
bw = null;
}
if (fw != null) {
fw.close();
fw = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
我的解决方案功能
private void close() {
try {
if (bw != null) {
bw.flush();
bw = null;
}
if (fw != null) {
fw.flush();
fw = null;
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
现在我的答案是,是否可以不关闭流并仅与flush一起使用? 以后还会有问题吗?因为在我的所有测试中它都运行良好。
谢谢!!
最佳答案
以一种非常谦虚的方式诚实一点可以吗?抱歉,代码很臭:
- 为什么设置为空“bw”和“fw”?全局变量?为什么?
- “例如.printStackTrace();” ?真的吗?没有 log4j 或类似的东西?
- 为什么不使用finally block ?如果读写文件时发生异常怎么办?
- 有人已经回答了这个问题,代码请引用这个优秀的答案:
Is it necessary to close a FileWriter, provided it is written through a BufferedWriter?
关于java - 在java中写入文件 - 关闭或刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42921805/