简体   繁体   中英

Writing in same file from different classes in java

How do I write in same text file from different classes in java. One of the class call method from another class.

I do not want to open BufferedWriter in each class, so thinking if there is a cleaner way to do this ?

So essentially, I want to avoid writing the following code in each class

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

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

A good way of doing this is to create a central writing class, that maps from a file name to a reader/writer-object. For example:

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);
    }
}

Be aware that this behavior does not close the file writers at any point, because you don't know who else is currently (or later on) writing. This is not a complete solution, just a strong hint in a good direction.

This is cool, because now you can "always" call FileHandler.write("c:output.txt", "Hello something!?$"); . The FileHandler class could be extended (as hinted) to read files too, and to do other stuff for you, that you might need later (like buffer the content, so you don't have to read a file every time you access it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM