首页 > 解决方案 > 从java中的不同类写入同一个文件

问题描述

如何从 java 中的不同类写入相同的文本文件。另一个类的类调用方法之一。

我不想BufferedWriter在每个班级都开课,所以想想是否有更清洁的方法来做到这一点?

所以本质上,我想避免在每个类中编写以下代码

Path path = Paths.get("c:/output.txt");

try (BufferedWriter writer = Files.newBufferedWriter(path)) {
   writer.write("Hello World !!");
}

标签: javafilebufferedwriter

解决方案


这样做的一个好方法是创建一个中央写入类,它从文件名映射到读取器/写入器对象。例如:

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 类也可以扩展(如提示的那样)以读取文件,并为您做其他事情,您以后可能需要(例如缓冲内容,因此您不必每次访问文件时都读取它) .


推荐阅读