[英]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.