I have a method called ReadTill that has the same body of code but different parameter types. Could someone show me a strategy / code to combine them. I don’t think that InputStream and BufferedReader share an interface, if they do, what is it and also if they didn’t how would I do this?
I think the question should be, how can I do this with generics?
Thanks in advance.
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);
}
}
}
Those classes (
InputStream,BufferedReader)does not implement the same interfaces nor extend the same class, but you can creat one from the other:And usually, Java method names are camelCase, so I changed it in the example.