Avinash
Avinash

Reputation: 195

creating a constructor for file creation

I am writing a program based on file. My code looks something like this,

   public class clazz {
    void somemethod() {
        StringBuffer s = new StringBuffer();
        // some code at final
        write(buf);
    }

    void write(StringBuffer buffer) {
        FileWriter f = new FileWriter(fileName);
        BufferedWriter b = new BufferedWriter(f);
        // implemented write, flush, close
    }
}

when I call somemethod method, the file gets open every time. I need to open the file once using constructor and reuse the BufferedWriter. Help me regarding this.

Upvotes: 0

Views: 208

Answers (1)

Nishant
Nishant

Reputation: 55866

It looks like something that your adviser told you to do and you have no clue.

  1. Make BufferedWriter a instance variable
  2. Initialize it in your constructor.

Upvotes: 2

Related Questions