我要方法。一个从文件读取,另一个写入它。如果要查看它们,它们只在局部变量中有所不同:
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?
答案 0 :(得分:0)
将常见部分划分为方法:
void handle(...) {
// handle exception
}
public void read(...) {
try {
...
} catch (...) {
handle(...); // use defined method
}
}
public void write(...) {
try {
...
} catch (...) {
handle(...); // and here
}
}