我有一个名为 ReadTill
的方法,它具有相同的代码主体,但参数类型不同。有人可以告诉我一个将它们结合起来的策略/代码吗?我不认为 InputStream
和 BufferedReader
共享一个接口(interface),如果它们共享一个接口(interface),那么它是什么,如果它们不共享我该怎么做?
我认为问题应该是,我该如何使用泛型来做到这一点?
提前致谢。
public static void ReadTill(InputStream in, OutputStream out, String end) throws IOException {
int c, pos = 0;
StringBuffer temp = new StringBuffer();
while ((c = in.read()) != -1) {
char cc = (char) c;
if (end.charAt(pos++) == cc) {
if (pos >= end.length()) {
break;
}
temp.append(cc);
} else {
pos = 0;
if (temp.length() > 0) {
out.write(temp.toString().getBytes());
temp.setLength(0);
}
out.write(cc);
}
}
}
public static void ReadTill(BufferedReader in, OutputStream out, String end) throws IOException {
int c, pos = 0;
StringBuffer temp = new StringBuffer();
while ((c = in.read()) != -1) {
char cc = (char) c;
if (end.charAt(pos++) == cc) {
if (pos >= end.length()) {
break;
}
temp.append(cc);
} else {
pos = 0;
if (temp.length() > 0) {
out.write(temp.toString().getBytes());
temp.setLength(0);
}
out.write(cc);
}
}
}
最佳答案
这些类(InputStream
、BufferedReader
)既不实现相同的接口(interface),也不扩展相同的类,但您可以从另一个类创建一个:
public static void readTill(InputStream in, OutputStream out, String end) throws IOException {
readTill(new BufferedReader(new InputStreamReader(in)), out, end);
}
public static void readTill(BufferedReader in, OutputStream out, String end) throws IOException {
// as before
}
通常,Java 方法名称都是驼峰命名法,所以我在示例中更改了它。
关于Java重复方法合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9961833/