[英]Writing in same file from different classes in java
如何在Java中使用不同类别的同一个文本文件进行编写。 来自另一个类的一个类调用方法。
我不想在每个类中都打开BufferedWriter
,所以想想是否有一种更干净的方法?
所以从本质上讲,我想避免在每个类中编写以下代码
Path path = Paths.get("c:/output.txt");
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write("Hello World !!");
}
做到这一点的一种好方法是创建一个中央写作类,该类从文件名映射到读取器/写入器对象。 例如:
public class FileHandler {
private static final Map<String, FileHandler> m_handlers = new HashMap<>();
private final String m_path;
private final BufferedWriter m_writer;
// private final BufferedReader m_reader; this one is optional, and I did not instantiate in this example.
public FileHandler (String path) {
m_path = path;
try {
m_writer = Files.newBufferedWriter(path);
} catch (Exception e) {
m_writer = null;
// some exception handling here...
}
}
public void write(String toWrite) {
if (m_writer != null) {
try {
m_writer.write(toWrite);
} catch (IOException e) {
// some more exception handling...
}
}
}
public static synchronized void write(String path, String toWrite) {
FileHandler handler = m_handlers.get(path);
if (handler == null) {
handler = new FileHandler(path);
m_handlers.put(path, toWrite);
}
handler.write(toWrite);
}
}
请注意,此行为不会在任何时候关闭文件编写器,因为您不知道当前(或稍后)还有谁在写文件。 这不是一个完整的解决方案,只是朝着正确方向的有力暗示。
这很酷,因为现在您可以“始终”调用FileHandler.write("c:output.txt", "Hello something!?$");
。 可以扩展FileHandler类(如提示)以读取文件,并为您做其他事情,以便您以后可能需要(例如缓冲内容,因此您不必在每次访问文件时都读取文件) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.