20非常有用的Java程序片段(19-20)

19. 發送代數據的HTTP 請求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
importjava.io.BufferedReader;  
importjava.io.InputStreamReader;  
importjava.net.URL;  
publicclassMain {  
publicstaticvoidmain(String[] args)  {  
try{  
URL my_url = newURL("http://coolshell.cn/");  
BufferedReader br = newBufferedReader(newInputStreamReader(my_url.openStream()));  
String strTemp = "";  
while(null!= (strTemp = br.readLine())){  
System.out.println(strTemp);  
}  
} catch(Exception ex) {  
ex.printStackTrace();  
}  
}  
}

20. 改變數組的大小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Reallocates an array with a new size, and copies the contents
* of the old array to the new array.
* @param oldArray  the old array, to be reallocated.
* @param newSize   the new array size.
* @return          A new array with the same contents.
*/
privatestaticObject resizeArray (Object oldArray, intnewSize) {  
intoldSize = java.lang.reflect.Array.getLength(oldArray);  
Class elementType = oldArray.getClass().getComponentType();  
Object newArray = java.lang.reflect.Array.newInstance(  
elementType,newSize);  
intpreserveLength = Math.min(oldSize,newSize);  
if(preserveLength > 0)  
System.arraycopy (oldArray,0,newArray,0,preserveLength);  
returnnewArray;  
}  
// Test routine for resizeArray().  
publicstaticvoidmain (String[] args) {  
int[] a = {1,2,3};  
a = (int[])resizeArray(a,5);  
a[3] = 4;  
a[4] = 5;  
for(inti=0; i<a.length; i++)  
System.out.println (a[i]);  
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章