java - 从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 类也可以扩展(如提示的那样)以读取文件,并为您做其他事情,您以后可能需要(例如缓冲内容,因此您不必每次访问文件时都读取它) .
推荐阅读
- java - 从路径与列表集合中的图像到图像视图?
- android - 如何“将当前毕加索加载的图像设置为墙纸”
- html - 如何创建波浪形 CSS?
- sql - SQL Select 基于来自子查询的值
- java - 在本地模式下运行 Apache Storm 连接错误
- c# - 参数无效。在我的代码的 memorystream 行时出错。我将文件作为 jpeg 插入,但我不知道它为什么会失败
- printing - 从云端打印到办公室打印机
- javascript - Node Js、javascript、mysql,客户端看到/看不到什么?
- html - 使我的标题“固定”调整标题框的大小
- c - 如何使用浮点数进行超时?