bufferedreader和bufferedwriter的java提取方法

时间:2015-06-25 23:12:28

标签: java extract bufferedreader bufferedwriter

我要方法。一个从文件读取,另一个写入它。如果要查看它们,它们只在局部变量中有所不同:

z-index

我想从两者中提取单个方法。并根据传入的对象是什么:打开文件或关闭它。像这样的Smth:

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

是否可以在同一方法下组合Writer和Reader?

1 个答案:

答案 0 :(得分:0)

将常见部分划分为方法:

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

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