2015-06-25 152 views
0

我必须采用这种方法。一个从文件读取,另一个写入文件。如果要看它们,它们只在局部变量上有所不同:java提取缓冲读取器和缓冲写入器的方法

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

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

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

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

+0

没有,没有办法统一阅读和写作。但是你可能想要声明你的方法抛出IOException而不是捕获它。 – VGR

+0

我不认为这会是一个好主意,并不值得每个5行。但是,如果在创建BufferedReader/Writer之前或之后有大量常见的代码片段,则可以将这些片段分解为函数,并在/之前调用函数。 –

+0

* Roberto Attias *你能举个例子吗?请... – ovod

回答

0

Excract公用部分进入方法:

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

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