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?
没有,没有办法统一阅读和写作。但是你可能想要声明你的方法抛出IOException而不是捕获它。 – VGR
我不认为这会是一个好主意,并不值得每个5行。但是,如果在创建BufferedReader/Writer之前或之后有大量常见的代码片段,则可以将这些片段分解为函数,并在/之前调用函数。 –
* Roberto Attias *你能举个例子吗?请... – ovod