1

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 !!");
}
rdas
  • 20,604
  • 6
  • 33
  • 46
Andy897
  • 6,915
  • 11
  • 51
  • 86
  • 3
    a singleton utility class, with methods `openFile` `write` `close` – Scary Wombat Apr 24 '19 at 06:19
  • You can abstract this code above. – J_D Apr 24 '19 at 06:20
  • You have two options. 1. write in class and then close all streams and write in another class or 2. create one class that will provide writing to this file for you – MrHolal Apr 24 '19 at 06:20
  • also, you can make class and variable static – Dred Apr 24 '19 at 06:20
  • Thanks a lot everyone. 2nd option - create one class that will write to file .. sounds good. Isn't there a 3rd option as well? Any sample code/utility for option 2nd ? – Andy897 Apr 24 '19 at 06:26

1 Answers1

1

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).

TreffnonX
  • 2,924
  • 15
  • 23