以代碼來說話吧,以下是實現同一功能的兩段不同的代碼。
第一段,兩個FindChar類代碼的對比:
public static void main(String[] args) throws Exception{
if(2!=args.length){
throw new Exception("need char and file");
}
char ch = args[0].charAt(0);
FileReader fileIn = new FileReader(args[1]);
LineNumberReader in = new LineNumberReader(fileIn);
int r;
while(-1!=(r=in.read())){
if(ch==r){
System.out.println("char "+ch+" at line "+in.getLineNumber());
return;
}
}
System.out.println("char "+ch+" not found!");
}
}
public static void main(String[] args) throws IOException{
if(2!=args.length){
throw new IllegalArgumentException("need char and file");
}
int match = args[0].charAt(0);
FileReader fileIn = new FileReader(args[1]);
LineNumberReader in = new LineNumberReader(fileIn);
int ch;
while(-1!=(ch=in.read())){
if(match==ch){
System.out.println("'"+(char)ch+"' at line "+in.getLineNumber());
return;
}
}
System.out.println("'"+(char)match+"' not found!");
}
}
第二段,兩個Concat 類代碼的對比:
public static void main(String[] args) throws IOException {
InputStream in;
// 如果無參數,則用System.in做爲輸入流,或者取出參數對應的文件做爲輸入流
if(0==args.length)
in = System.in;
else{
ArrayList<BufferedInputStream> arrayList = new ArrayList<BufferedInputStream>(args.length);
for(int i=0; i<args.length; i++){
FileInputStream fi = new FileInputStream(args[i]);
BufferedInputStream bi = new BufferedInputStream(fi);
arrayList.add(bi);
}
SequenceInputStream si = new SequenceInputStream(Collections.enumeration(arrayList));
in = si;
}
// 把輸入流中的信息輸出到控制檯上來
int ch;
while(-1!=(ch=in.read()))
System.out.write(ch); // 用write方法,用print輸出漢字會有問題
System.out.flush(); // 調用flush方法,否則看不到輸出
}
}
public static void main(String[] args) throws IOException {
InputStream in;
// 如果無參數,則用System.in做爲輸入流,或者取出參數對應的文件做爲輸入流
if(0==args.length)
in = System.in;
else{
InputStream fileIn,buffIn;
List<InputStream> inputs = new ArrayList<InputStream>(args.length);
for(int i=0; i<args.length; i++){
fileIn = new FileInputStream(args[i]);
buffIn = new BufferedInputStream(fileIn);
inputs.add(buffIn);
}
Enumeration<InputStream> files = Collections.enumeration(inputs);
in = new SequenceInputStream(files);
}
// 把輸入流中的信息輸出到控制檯上來
int ch;
while(-1!=(ch=in.read()))
System.out.write(ch); // 用write方法,用print輸出漢字會有問題
System.out.flush(); // 調用flush方法,否則看不到輸出
}
}
結論:差別很大。