1

Is there a way that i can Get the file it being written in case of FileWirter. I dont have any reference to the File object with me.

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

How can I get the File that got created in this case. I will access thefile only after the writer is closed..But i dont want to keep a separate list of all the file created. Whats the best way.

Ysak
  • 2,601
  • 6
  • 29
  • 53

3 Answers3

2

You just need to save a reference to the File:

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 */
}
Patrick Parker
  • 4,863
  • 4
  • 19
  • 51
1

Since you can't get the file before the super call

Initialize field before super constructor runs?

You could try something like this

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

You may want to implement these interfaces if you want the full functionality of a filewriter-like object

Closeable, Flushable, Appendable, AutoCloseable

Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
-1

According to the official document, there is no way to retrive the File object. And it's also not possible with FileWriter. However, by seeing the problm from a different perspective, you may come up like this (Assuming Job is your class. You can extend from Job if it's not):

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
}
quartzsaber
  • 174
  • 3
  • 10