2016-12-03 38 views
1

有沒有一種方法可以在FileWirter的情況下獲取正在寫入的文件。我沒有任何對File對象的引用。獲取FileWriter在Java中寫入的文件

public class JobResponseWriter extends FileWriter{ 
    public JobResponseWriter(Job job) throws IOException { 
     super(File.createTempFile("JobResponse" + job.getId() ,"tmp")); 
    } 

    public void writeLn(String str) throws IOException { 
     super.write(str + "\n"); 
    } 
} 

如何獲取在這種情況下創建的文件。我只能在編輯器關閉後才能訪問該文件。但我不想保留創建的所有文件的單獨列表。最好的方法是什麼。

+0

您是否必須使用超級構造函數來創建臨時文件? –

+0

我需要JobResponseWriter的行爲像一個FileWriter,如果你有任何其他的方式..讓我知道 – Ysak

+0

這是一個標準問題的「構成繼承」。你應該做一個'File'成員變量和直接擴展它 –

回答

2

你只需要保存到一個參考文件:

public class JobResponseWriter extends FileWriter{ 
    private final File myFile; 
    public JobResponseWriter(Job job) throws IOException { 
     this(File.createTempFile("JobResponse" + job.getId() ,"tmp")); 
    } 
    public JobResponseWriter(File f) throws IOException { 
     super(f); 
     myFile = f; 
    } 
    /* your code here */ 
} 
+0

啊,是的。並沒有考慮過這種方式 –

+0

這到底是什麼,我有我implemented..basically已取出文件的創建邏輯... – Ysak

1

既然你不能在超級調用之前得到的文件

Initialize field before super constructor runs?

你可以嘗試這樣的事情

public class JobResponseWriter { 

    private final File f; 
    private final fw; 

    public JobResponseWriter(Job job) throws IOException { 
     this.f = File.createTempFile("JobResponse" + job.getId() ,"tmp")); 
     this.fw = new FileWriter(f); 
    } 

    public void writeLn(String str) throws IOException { 
     fw.write(str + "\n"); 
    } 

    // public void getFile() 
} 

你可能想,如果你想充分實現這些接口類似於文件編寫者的對象的功能

Closeable, Flushable, Appendable, AutoCloseable

-1

根據official document,沒有辦法檢索File對象。而且這也不可能與FileWriter。然而,通過觀察從不同的角度對problm,你可能會想出這樣的(假設Job是你的類可以從Job延長,如果不是這樣的。):

public class JobResponseWriter extends FileWriter{ 
    File jobResponse = null; 
    public FileWriter getJobResponseWriter() { 
     if(jobResponse == null) 
      jobResponse = File.createTempFile("JobResponse" + getId() ,"tmp")); 
     return new FileWriter(jobResponse, true); //Open in append mode 
    } 

    public File getJobResponseFile() { 
     if(jobResponse == null) 
      jobResponse = File.createTempFile("JobResponse" + getId() ,"tmp")); 
     return jobResponse; 
    } 

    //And the original methods here 
} 
+0

呃......等等。我想我對C++感到困惑。可能不是這樣,但在方法''中。檢查後我會回來。 – minary

+0

這不是在Java中 – Ysak

+0

@Ysak可能的解決方案所以我編輯的代碼。我從不同的角度看待問題。它絕對應該工作。 – minary

相關問題