2012-04-01 63 views
0

我有一个名为ReadTill的方法,它具有相同的代码体但参数类型不同。有人可以给我看一个策略/代码来合并它们。我不认为InputStreamBufferedReader共享一个接口,如果他们这样做,它是什么,如果他们不怎么做我会怎么做?Java复制方法合并

我认为这个问题应该是,我如何用泛型来做到这一点?

在此先感谢。

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); 
     } 
    } 
} 
+0

为什么你想在这里使用泛型?当方法参数或变量实际上实际上是一个对象,但是被访问就好像它是用特定的类来键入的时候,泛型被用于这种情况。你的情况没有这样的变数。 – 2012-04-01 06:23:30

+0

@AlexeiKaigorodov理由: A)想清理代码,认为他们会 B)看看他们将如何用于教育目的。 – 2012-04-01 07:15:07

回答

2

这些类(InputStreamBufferedReader)没有实现相同的接口,也延长了同一类,但你可以创造一个从其他:

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方法名称是camelCase,所以我在示例中对其进行了更改。

+0

你知道我可以用泛型做到吗? – 2012-04-01 04:15:21

+1

由于我在答复顶部写的原因,我不确定这是可能的。 – MByD 2012-04-01 04:16:28

1

只是把我的头顶部,未经测试:

public static void ReadTill(InputStream in, OutputStream out, String end) throws IOException { 
ReadTill(new BufferedReader(new InputStreamReader(in)), out, end); 
}