java extract method for bufferedreader and bufferedwriter

152 views Asked by At

I have to methods. One reads from file, another writes to it. If to look at them, they differ only in local variable:

public method1 wtite() {
  try {
    BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
  } catch (here come catch cases equal in two methods)
}

public method1 read() {
  try {
    BufferedReader in = new BufferedReader(new FileReader(file));
  } catch (here come catch cases equal in two methods)
}

I want to extract a single method from both. And depending what the incoming object is: open file or close it. Smth like this:

public fileIO(??? io) {
  try{
    //read or write
  } catch//put the same code here
}

Is it possible to combine Writer and Reader under the same method?

1

There are 1 answers

0
cybersoft On

Excract common parts into methods:

void handle(...) {
    // handle exception
}

public void read(...) {
    try {
    ...
    } catch (...) {
        handle(...); // use defined method
    }
}
public void write(...) {
    try {
    ...
    } catch (...) {
        handle(...); // and here
    }
}