【发布时间】:2015-06-25 23:12:28
【问题描述】:
我必须要方法。一个从文件中读取,另一个写入文件。如果要查看它们,它们仅在局部变量上有所不同:
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)
}
我想从两者中提取一个方法。取决于传入的对象是什么:打开文件或关闭它。像这样的:
public fileIO(??? io) {
try{
//read or write
} catch//put the same code here
}
Writer 和 Reader 可以在同一个方法下合并吗?
【问题讨论】:
-
不行,没有办法统一读写。但是你可能想要声明你的方法来抛出 IOException 而不是捕获它。
-
我认为这不是一个好主意,而且每行 5 行都不值得。但是,如果您在创建 BufferedReader/Writer 之前或之后有大量通用代码,则可以将这些 sn-p 分解为函数,并在之前/之后调用函数。
-
Roberto Attias 你能举个例子吗?请...
标签: java extract bufferedreader bufferedwriter