Java經典實例(第二版)


1. 獲取環境變量

Java代碼 

1.    System.getenv("PATH");  

2.    System.getenv("JAVA_HOME");  

 

2. 獲取系統屬性

Java代碼 

1.    System.getProperty("pencil color");  // 得到屬性值  

2.    java -Dpencil color=green  

3.    System.getProperty("java.specification.version");  // 得到Java版本號  

4.    Properties p = System.getProperties();  // 得到所有屬性值  

5.    p.list(System.out);  

 

3. StringTokenizer

Java代碼 

1.    // 能夠同時識別, 和 |  

2.    StringTokenizer st = new StringTokenizer("Hello, World|of|Java", ", |");  

3.    while (st.hasMoreElements()) {  

4.        st.nextToken();  

5.    }  

6.      

7.    // 把分隔符視爲token  

8.    StringTokenizer st = new StringTokenizer("Hello, World|of|Java", ", |",  true);  

 

4. StringBuffer(同步)和StringBuilder(非同步)

Java代碼 

1.    StringBuilder sb = new StringBuilder();  

2.    sb.append("Hello");  

3.    sb.append("World");  

4.    sb.toString();  

5.    new StringBuffer(a).reverse();   // 反轉字符串  

 

5. 數字

Java代碼 

1.    // 數字與對象之間互相轉換 - Integer轉int  

2.    Integer.intValue();  

3.      

4.    // 浮點數的舍入    

5.    Math.round()  

6.      

7.    // 數字格式化  

8.    NumberFormat  

9.      

10.    // 整數 -> 二進制字符串  

11.    toBinaryString() 或valueOf()  

12.      

13.    // 整數 -> 八進制字符串  

14.    toOctalString()  

15.      

16.    // 整數 -> 十六進制字符串  

17.    toHexString()  

18.      

19.    // 數字格式化爲羅馬數字  

20.    RomanNumberFormat()  

21.      

22.    // 隨機數  

23.    Random r = new Random();  

24.    r.nextDouble();  

25.    r.nextInt();  

 

6. 日期和時間

Java代碼 

1.    // 查看當前日期  

2.    Date today = new Date();  

3.    Calendar.getInstance().getTime();  

4.      

5.    // 格式化默認區域日期輸出  

6.    DateFormat df = DateFormat.getInstance();  

7.    df.format(today);  

8.      

9.    // 格式化制定區域日期輸出        

10.    DateFormat df_cn = DateFormat.getDateInstance(DateFormat.FULL, Locale.CHINA);  

11.    String now = df_cn.format(today);  

12.      

13.    // 按要求格式打印日期  

14.    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  

15.    sdf.format(today);  

16.      

17.    // 設置具體日期  

18.    GregorianCalendar d1 = new GregorianCalendar(2009, 05, 06);  // 6月6日  

19.    GregorianCalendar d2 = new GregorianCalendar();  // 今天  

20.    Calendar d3 = Calendar.getInstance();  // 今天  

21.    d1.getTime();  // Calendar或GregorianCalendar轉成Date格式  

22.    d3.set(Calendar.YEAR, 1999);  

23.    d3.set(Calendar.MONTH, Calendar.APRIL);  

24.    d3.set(Calendar.DAY_OF_MONTH, 12);  

25.      

26.    // 字符串轉日期  

27.    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  

28.    Date now = sdf.parse(String);  

29.      

30.    // 日期加減  

31.    Date now = new Date();  

32.    long t = now.getTime();  

33.    t += 700*24*60*60*1000;  

34.    Date then = new Date(t);  

35.      

36.    Calendar now = Calendar.getInstance();  

37.    now.add(Calendar.YEAR, -2);  

38.      

39.    // 計算日期間隔(轉換成long來計算)  

40.    today.getTime() - old.getTime();  

41.      

42.    // 比較日期  

43.    Date 類型,就使用equals(), before(), after()來計算  

44.    long類型,就使用==, <, >來計算  

45.      

46.    // 第幾日  

47.    使用 Calendar的get()方法  

48.    Calendar c = Calendar.getInstance();  

49.    c.get(Calendar.YEAR);   

50.      

51.    // 記錄耗時  

52.    long start = System.currentTimeMillis();  

53.    long end = System.currentTimeMillis();  

54.    long elapsed = end - start;  

55.    System.nanoTime();  //毫秒  

56.      

57.    // 長整形轉換成秒  

58.    Double.toString(t/1000D);  

 

7. 結構化數據

Java代碼 

1.    // 數組拷貝  

2.    System.arrayCopy(oldArray, 0, newArray, 0, oldArray.length);  

3.      

4.    // ArrayList  

5.    add(Object o)  // 在末尾添加給定元素  

6.    add(int i, Object o)  // 在指定位置插入給定元素  

7.    clear()  // 從集合中刪除全部元素  

8.    Contains(Object o)  // 如果Vector包含給定元素,返回真值  

9.    get(int i)  // 返回 指定位置的對象句柄  

10.    indexOf(Object o)  // 如果找到給定對象,則返回其索引值;否則,返回-1  

11.    remove(Object o)  // 根據引用刪除對象  

12.    remove(int i)  // 根據 位置刪除對象  

13.    toArray()  // 返回包含集合對象的數組  

14.      

15.    // Iterator  

16.    List list = new ArrayList();  

17.    Iterator it = list.iterator();  

18.    while (it.hasNext())  

19.    Object o = it.next();  

20.      

21.    // 鏈表  

22.    LinkedList list = new LinkedList();  

23.    ListIterator it = list.listIterator();  

24.    while (it.hasNext())  

25.    Object o = it.next();  

26.      

27.    // HashMap  

28.    HashMap<String, String> hm = new HashMap<String, String>();  

29.    hm.get(key);  // 通過key得到value  

30.    hm.put("No1", "Hexinyu");  

31.    hm.put("No2", "Sean");  

32.    // 方法1: 獲取全部鍵值    

33.    Iterator<String> it = hm.values().iterator();   

34.    while (it.hasNext()) {  

35.        String myKey = it.next();  

36.        String myValue = hm.get(myKey);  

37.    }  

38.    // 方法2: 獲取全部鍵值        

39.    for (String key : hm.keySet()) {  

40.        String myKey = key;  

41.        String myValue = hm.get(myKey);  

42.    }  

43.      

44.    // Preferences - 與系統相關的用戶設置,類似名-值對  

45.    Preferences prefs = Preferences.userNodeForPackage(ArrayDemo.class);  

46.    String text = prefs.get("textFontName", "lucida-bright");  

47.    String display = prefs.get("displayFontName", "lucida-balckletter");  

48.    System.out.println(text);  

49.    System.out.println(display);  

50.    // 用戶設置了新值,存儲回去       

51.    prefs.put("textFontName", "new-bright");  

52.    prefs.put("displayFontName", "new-balckletter");  

53.      

54.    // Properties - 類似名-值對,key和value之間,可以用"=",":"或空格分隔,用"#" 和"!"註釋  

55.    InputStream in = MediationServer.class.getClassLoader().getResourceAsStream("msconfig.properties");  

56.    Properties prop = new Properties();  

57.    prop.load(in);  

58.    in.close();  

59.    prop.setProperty(key, value);  

60.    prop.getProperty(key);  

61.      

62.    // 排序  

63.    1. 數組:Arrays.sort(strings);  

64.    2. List:Collections.sort(list);  

65.    3. 自定義類:class SubComp implements Comparator  

66.        然 後使用Arrays.sort(strings, new SubComp())  

67.         

68.    // 兩個接口  

69.    1. java.lang.Comparable: 提供對象的自然排序,內置於類中  

70.       int compareTo(Object o);  

71.        boolean equals(Object o2);  

72.    2. java.util.Comparator: 提供特定的比較方法  

73.       int compare(Object o1, Object o2)  

74.         

75.    // 避免重複排序,可以使用TreeMap  

76.    TreeMap sorted = new TreeMap(unsortedHashMap);  

77.      

78.    // 排除重複元素  

79.    Hashset hs - new HashSet();  

80.      

81.    // 搜索對象  

82.    binarySearch(): 快 速查詢 - Arrays, Collections  

83.    contains(): 線型搜 索 - ArrayList, HashSet, Hashtable, linkedList, Properties, Vector  

84.    containsKey(): 檢 查集合對象是否包含給定 - HashMap, Hashtable, Properties, TreeMap  

85.    containsValue(): 主 鍵(或給定值) - HashMap, Hashtable, Properties, TreeMap  

86.    indexOf(): 若 找到給定對象,返回其位置 - ArrayList, linkedList, List, Stack, Vector  

87.    search(): 線 型搜素 - Stack  

88.      

89.    // 集合轉數組  

90.    toArray();  

91.      

92.    // 集合總結  

93.    Collection: Set - HashSet, TreeSet  

94.    Collection: List - ArrayList, Vector, LinkedList  

95.    Map: HashMap, HashTable, TreeMap  

 

8. 泛型與foreach

Java代碼 

1.    // 泛型  

2.    List<String> myList = new ArrayList<String>();  

3.      

4.    // foreach  

5.    for (String s : myList) {  

6.        System.out.println(s);  

7.    }  

 

9. 面向對象

Java代碼 

1.    // toString()格式化  

2.    public class ToStringWith {  

3.        int x, y;  

4.        public ToStringWith(int anX, int aY) {  

5.            x = anX;  

6.            y = aY;  

7.        }  

8.        public String toString() {  

9.            return "ToStringWith[" + x + "," + y + "]";  

10.        }  

11.        public static void main(String[] args) {  

12.            System.out.println(new ToStringWith(43, 78));  

13.        }  

14.    }  

15.      

16.    // 覆蓋equals方法  

17.    public boolean equals(Object o) {  

18.        if (o == this)  // 優化  

19.            return true;  

20.        if (!(o instanceof EqualsDemo))  // 可投射到這個類  

21.            return false;  

22.        EqualsDemo other = (EqualsDemo)o;  // 類型轉換  

23.        if (int1 != other.int1)  // 按字段比較  

24.            return false;  

25.        if (!obj1.equals(other.obj1))  

26.            return false;  

27.        return true;  

28.    }  

29.      

30.    // 覆蓋hashcode方法  

31.    private volatile int hashCode = 0;  //延遲初始化  

32.    public int hashCode() {  

33.        if (hashCode == 0) {  

34.            int result = 17;  

35.            result = 37 * result + areaCode;  

36.        }  

37.        return hashCode;  

38.    }  

39.      

40.    // Clone方法  

41.    要 克隆對象,必須先做兩步: 1. 覆蓋對象的clone()方法; 2. 實現空的Cloneable接口  

42.    public class Clone1 implements Cloneable {  

43.        public Object clone() {  

44.            return super.clone();  

45.        }  

46.    }  

47.      

48.    // Finalize方法  

49.    Object f = new Object() {  

50.        public void finalize() {  

51.            System.out.println("Running finalize()");  

52.        }  

53.    };        

54.    Runtime.getRuntime().addShutdownHook(new Thread() {  

55.        public void run() {  

56.            System.out.println("Running Shutdown Hook");  

57.        }  

58.    });  

59.    在 調用System.exit(0);的時候,這兩個方法將被執行  

60.      

61.    // Singleton模式  

62.    // 實現1  

63.    public class MySingleton() {  

64.        public static final MySingleton INSTANCE = new MySingleton();  

65.        private MySingleton() {}  

66.    }  

67.    // 實現2  

68.    public class MySingleton() {  

69.        public static MySingleton instance = new MySingleton();  

70.        private MySingleton() {}  

71.        public static MySingleton getInstance() {  

72.            return instance;  

73.        }  

74.    }  

75.      

76.    // 自定義異常  

77.    Exception: 編 譯時檢查  

78.    RuntimeException: 運行時檢查  

79.    public class MyException extends RuntimeException {  

80.        public MyException() {  

81.            super();  

82.        }  

83.        public MyException(String msg) {  

84.            super(msg);  

85.        }  

86.    }  

 

10. 輸入和輸出

Java代碼 

1.    // Stream, Reader, Writer  

2.    Stream: 處 理字節流  

3.    Reader/Writer: 處理字符,通用Unicode  

4.      

5.    // 從標準輸入設備讀數據  

6.    1. 用System.in的BufferedInputStream()讀取字節  

7.        int b = System.in.read();  

8.          System.out.println("Read data: " + (char)b);  // 強 制轉換爲字符  

9.    2. BufferedReader 讀取文本  

10.        如果從Stream轉成Reader,使用 InputStreamReader類  

11.        BufferedReader is = new BufferedReader(new   

12.          InputStreamReader(System.in));  

13.          String inputLine;  

14.          while ((inputLine = is.readLine()) != null) {  

15.              System.out.println(inputLine);  

16.              int val = Integer.parseInt(inputLine);  // 如果inputLine爲整數  

17.        }  

18.          is.close();  

19.          

20.    // 向標準輸出設備寫數據  

21.    1. 用System.out的println()打印數據  

22.    2. 用PrintWriter打印  

23.        PrintWriter pw = new PrintWriter(System.out);  

24.          pw.println("The answer is " + myAnswer + " at this time.");  

25.          

26.    // Formatter類  

27.    格 式化打印內容  

28.    Formatter fmtr = new Formatter();  

29.    fmtr.format("%1$04d - the year of %2$f", 1951, Math.PI);  

30.    或 者System.out.printf();或者System.out.format();        

31.      

32.    // 原始掃描  

33.    void doFile(Reader is) {  

34.        int c;  

35.        while ((c = is.read()) != -1) {  

36.            System.out.println((char)c);  

37.        }  

38.    }    

39.      

40.    // Scanner掃描  

41.    Scanner 可以讀取File, InputStream, String, Readable  

42.    try {  

43.        Scanner scan = new Scanner(new File("a.txt"));  

44.        while (scan.hasNext()) {  

45.            String s = scan.next();  

46.        }  

47.        } catch (FileNotFoundException e) {  

48.            e.printStackTrace();  

49.        }  

50.    }  

51.      

52.    // 讀取文件  

53.    BufferedReader is = new BufferedReader(new FileReader("myFile.txt"));  

54.    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bytes.bat"));  

55.    is.close();  

56.    bos.close();  

57.      

58.    // 複製文件  

59.    BufferedIutputStream is = new BufferedIutputStream(new FileIutputStream("oldFile.txt"));  

60.    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream("newFile.txt"));  

61.    int b;  

62.    while ((b = is.read()) != -1) {  

63.        os.write(b);  

64.    }  

65.    is.close();  

66.    os.close();  

67.      

68.    // 文件讀入字符串  

69.    StringBuffer sb = new StringBuffer();  

70.    char[] b = new char[8192];  

71.    int n;  

72.    // 讀一個塊,如果有字符,加入緩衝區  

73.    while ((n = is.read(b)) > 0) {  

74.        sb.append(b, 0, n);  

75.    }  

76.    return sb.toString();  

77.      

78.    // 重定向標準流  

79.    String logfile = "error.log";  

80.    System.setErr(new PrintStream(new FileOutputStream(logfile)));  

81.      

82.    // 讀寫不同字符集文本  

83.    BufferedReader chinese = new BufferedReader(new InputStreamReader(new FileInputStream("chinese.txt"), "ISO8859_1"));  

84.    PrintWriter standard = new PrintWriter(new OutputStreamWriter(new FileOutputStream("standard.txt"), "UTF-8"));  

85.      

86.    // 讀取二進制數據  

87.    DataOutputStream os = new DataOutputStream(new FileOutputStream("a.txt"));  

88.    os.writeInt(i);  

89.    os.writeDouble(d);  

90.    os.close();  

91.      

92.    // 從指定位置讀數據  

93.    RandomAccessFile raf = new RandomAccessFile(fileName, "r");  // r表示已 只讀打開  

94.    raf.seek(15);  // 從15開始讀  

95.    raf.readInt();  

96.    raf.radLine();  

97.      

98.    // 串行化對象  

99.    對象串 行化,必須實現Serializable接口  

100.    // 保存 數據到磁盤  

101.    ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILENAME)));  

102.    os.writeObject(serialObject);  

103.    os.close();  

104.    // 讀出數據  

105.    ObjectInputStream is = new ObjectInputStream(new FileInputStream(FILENAME));  

106.    is.readObject();  

107.    is.close();  

108.      

109.    // 讀寫Jar或Zip文檔  

110.    ZipFile zippy = new ZipFile("a.jar");  

111.    Enumeration all = zippy.entries();  // 枚舉值列出所有文件清單  

112.    while (all.hasMoreElements()) {  

113.        ZipEntry entry = (ZipEntry)all.nextElement();  

114.        if (entry.isFile())  

115.            println("Directory: " + entry.getName());  

116.              

117.        // 讀寫文件  

118.        FileOutputStream os = new FileOutputStream(entry.getName());  

119.        InputStream is = zippy.getInputStream(entry);  

120.        int n = 0;  

121.        byte[] b = new byte[8092];  

122.        while ((n = is.read(b)) > 0) {  

123.            os.write(b, 0, n);  

124.            is.close();  

125.            os.close();  

126.        }  

127.    }  

128.      

129.    // 讀寫gzip文檔  

130.    FileInputStream fin = new FileInputStream(FILENAME);  

131.    GZIPInputStream gzis = new GZIPInputStream(fin);  

132.    InputStreamReader xover = new InputStreamReader(gzis);  

133.    BufferedReader is = new BufferedReader(xover);  

134.    String line;  

135.    while ((line = is.readLine()) != null)  

136.        System.out.println("Read: " + line);  

 

11. 目錄和文件操作

Java代碼 

1.    // 獲取文件信息  

2.    exists(): 如 果文件存在,返回true  

3.    getCanonicalPath(): 獲 取全名  

4.    getName(): 文件名  

5.    getParent(): 父 目錄  

6.    canRead(): 如果文件可讀,返回true  

7.    canWrite(): 如 果文件可寫,返回true  

8.    lastModified(): 文 件更新時間  

9.    length(): 文件大小  

10.    isFile(): 如 果是文件,返回true  

11.    ifDirectory(): 如 果是目錄,返回true  

12.    要 調用文件的這些方法,必須  

13.    File f = new File(fileName);  

14.      

15.    // 創建文件  

16.    File f = new File("c:\\test\\mytest.txt");  

17.    f.createNewFile();  // 創建mytest.txt文件到test目錄下  

18.      

19.    // 修改文件名  

20.    File f = new File("c:\\test\\mytest.txt");  

21.    f.renameTo(new File("c:\\test\\google.txt"));  

22.    把 mytest.txt修改成google.txt  

23.      

24.    // 刪除文件  

25.    File f = new File("c:\\test\\mytest.txt");  

26.    f.delete();  

27.      

28.    // 臨時文件  

29.    File f = new File("C:\\test");  // 指定一個文件夾  

30.    // 在test文件夾中創建foo前綴,tmp後綴的臨時文件  

31.    File tmp = File.createTempFile("foo", "tmp", f);   

32.    tmp.deleteOnExit();  // 在程序結束時刪除該臨時文件  

33.      

34.    // 更改文件屬性  

35.    setReadOnly(): 設 置爲只讀  

36.    setlastModified(): 設置最後更改時間  

37.      

38.    // 列出當前文件夾的文件列表  

39.    String[] dir = new java.io.File(".").list();  

40.    java.util.Arrays.sort(dir);  

41.    for (int i = 0; i < dir.length; i++) {  

42.        System.out.println(dir[i]);  

43.    }  

44.      

45.    // 過濾文件列表  

46.    class OnlyJava implements FilenameFilter {  

47.        public boolean accept(File dir, String s) {  

48.            if (s.endsWith(".java") || s.endsWith(".class") || s.endsWith(".jar"))  

49.                return true;  

50.        }  

51.    }  

52.      

53.    // 獲取根目錄  

54.    File[] rootDir = File.listRoots();  

55.    for (int i = 0; i < rootDir.length; i++) {  

56.        System.out.println(rootDir[i]);  

57.    }  

58.      

59.    // 創建新目錄  

60.    new File("/home/ian/bin").mkdir();  // 如果"/home/ian"存在,則可以創建bin目錄  

61.    new File("/home/ian/bin").mkdirs();  // 如果"/home/ian"不存在,會創建所有的目錄  

 

12. 國際化和本地化

Java代碼 

1.    // I18N資源  

2.    ResourceBundle rb = ResourceBundle.getBundle("Menus");  

3.    String label = rb.getString("exit.label");  

4.    // ResourceBundle相當於名值對,獲取Menus按鈕的區域屬性  

5.    Menus_cn.properties: 不 同區域的屬性文件  

6.      

7.    // 列出有效區域  

8.    Locale[] list = Locale.getAvailableLocales();  

9.      

10.    // 指定區域  

11.    Locale cnLocale = Locale.CHINA;  

12.      

13.    // 設置默認區域  

14.    Locale.setDefault(Locale.CHINA);  

15.      

16.    // 格式化消息  

17.    public class MessageFormatDemo {  

18.        static Object[] data = {  

19.            new java.util.Date(),  

20.            "myfile.txt",  

21.            "could nto be opened"  

22.        };  

23.        public static void main(String[] args) {  

24.            String result = MessageFormat.format("At {0,time} on {0,date}, {1} {2}.", data);  

25.            System.out.println(result);  

26.        }  

27.    }  

28.    輸 出: At 10:10:08 on 2009-6-18, myfile.txt could nto be opened.  

29.      

30.    // 從資源文件中讀消息  

31.    Widgets.properties 在com.sean.cook.chap11下  

32.    ResourceBundle rb = ResourceBundle.getBundle("com.sean.cook.chap11.Widgets");  

33.    String propt = rb.getString("filedialogs.cantopen.string");  

34.    String result = MessageFormat.format(rb.getString("filedialogs.cantopen.format"), data);  

 

13. 網絡客戶端

Java代碼 

1.    // 訪問服務器  

2.    Socket socket = new Socket("127.0.0.1", 8080);  

3.    // todo something  

4.    socket.close();  

5.      

6.    // 查找網絡地址  

7.    InetAddress.getByName(hostName).getHostAddress()); // 根據主機名得到IP地址  

8.    InetAddress.getByName(ipAddr).getHostName()); // 根據IP地址得到主機名  

9.      

10.    // 連接具體異常  

11.    UnknownHostException  

12.    NoRouteToHostException  

13.    ConnectException  

14.      

15.    // Socket讀寫文本數據  

16.    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));  

17.    String remoteTime = in.readline();  

18.    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);  

19.    out.print("send message to client \r\n");  

20.    out.flush();  

21.      

22.    // Socket讀寫二進制數據  

23.    DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));  

24.    long remoteTime = (long)(in.readUnsignedByte() << 24);  

25.    DataOutputStream out = new DataOutputStream(socket.getOutputStream(), true);  

26.      

27.    // Socket讀寫串行化數據  

28.    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));  

29.    Object o = in.readObject();  

30.    if (o instanceof Date) // 驗證對象類型  

31.    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream(), true);  

32.      

33.    // UDP數據報  

34.    private final static int PACKET_SIZE = 1024;  

35.          

36.    String host = "EV001B389673DE";  

37.    InetAddress serverAddr = InetAddress.getByName(host);  

38.    DatagramSocket socket = new DatagramSocket();  

39.    byte[] buffer = new byte[PACKET_SIZE]; // 分配數據緩衝空間  

40.    DatagramPacket packet = new DatagramPacket(buffer, PACKET_SIZE, serverAddr, 8080);  

41.    packet.setLength(PACKET_SIZE-1); // 設置數據長度  

42.    socket.send(packet);  

43.    socket.receive(packet); // 接收數據  

 

14. 服務器端: Socket 

Java代碼 

1.    // 創建ServerSocket  

2.    ServerSocket serverSocket;  

3.    Socket clientSocket;  

4.              

5.    serverSocket = new ServerSocket(9999);  

6.    while ((clientSocket = serverSocket.accept()) != null) {  

7.        System.out.println("Accept from client " + s.getInetAddress());  

8.        s.close();  

9.    }  

10.      

11.    // 監聽內部網  

12.    public static final short PORT = 9999;  

13.    public static final String INSIDE_HOST = "acmewidgets-inside"; // 網絡接口名  

14.    public static final int BACKLOG = 10; // 待發數  

15.    serverSocket = new ServerSocket(PORT, BACKLOG, InetAddress.getByName(INSIDE_HOST));  

16.      

17.    // 返回相應對象  

18.    ServerSocket serverSocket =  new ServerSocket(9999);;  

19.    Socket clientSocket;  

20.    BufferedReader in = null;  

21.    PrintWriter out = null;  

22.    while (true) {  

23.        clientSocket = serverSocket.accept();  

24.        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "8859_1"));  

25.        out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "8859_1"), true);  

26.        String echoLine;  

27.        while ((echoLine = in.readLine()) != null) {  

28.            System.out.println("Read " + echoLine);  

29.            out.print(echoLine + "\r\n");  

30.        }  

31.    }  

32.    以 上例子返回字符串,如果返回二進制,則使用DataOutputStream;返回對象,使用ObjectOutputStream  

33.      

34.    // 處理多客戶端  

35.    需要 把接收數據的處理放入多線程中  

36.    public class EchoServerThreaded {  

37.        public static final int ECHOPORT = 7;  

38.        public static final int NUM_THREADS = 4;  

39.      

40.        public static void main(String[] av) {  

41.            new EchoServerThreaded(ECHOPORT, NUM_THREADS);  

42.        }  

43.      

44.        public EchoServerThreaded2(int port, int numThreads) {  

45.            ServerSocket servSock;  

46.            Socket clientSocket;  

47.            try {  

48.                servSock = new ServerSocket(ECHOPORT);  

49.            } catch(IOException e) {  

50.                throw new RuntimeException("Could not create ServerSocket " + e);  

51.            }  

52.            for (int i = 0; i < numThreads; i++) {  

53.                new Handler(servSock, i).start();  

54.            }  

55.        }  

56.    }  

57.    class Handler extends Thread {  

58.        ServerSocket servSock;  

59.        int threadNumber;  

60.      

61.        Handler(ServerSocket s, int i) {  

62.            super();  

63.            servSock = s;  

64.            threadNumber = i;  

65.            setName("Thread " + threadNumber);  

66.        }  

67.      

68.        public void run() {  

69.            while (true) {  

70.                try {  

71.                    System.out.println(getName() + " waiting");  

72.                    Socket clientSocket;  

73.                    synchronized (servSock) {  

74.                        clientSocket = servSock.accept();  

75.                    }  

76.                    System.out.println(getName() + " starting, IP=" + clientSocket.getInetAddress());  

77.                    BufferedReader is = new BufferedReader(new InputStreamReader(  

78.                        clientSocket.getInputStream()));  

79.                    PrintStream os = new PrintStream(clientSocket.getOutputStream(), true);  

80.                    String line;  

81.                    while ((line = is.readLine()) != null) {  

82.                        os.print(line + "\r\n");  

83.                        os.flush();  

84.                    }  

85.                    System.out.println(getName() + " ENDED ");  

86.                    clientSocket.close();  

87.                } catch (IOException ex) {  

88.                    System.out.println(getName() + ": IO Error on socket " + ex);  

89.                    return;  

90.                }  

91.            }  

92.        }  

93.    }  

94.      

95.    // 使用SSL和JSSE保護Web服務器  

96.    SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();  

97.    ServerSocket serverSocket = ssf.createServerSocket(8080);  

98.      

99.    // Log4j  

100.    Level 級別: DEBUG < INFO < WARN < ERROR < FATAL < OFF  

101.    Appender: 輸 出信息  

102.    ConsoleAppender: 輸出控制檯 System.out  

103.      

104.    // 找到網絡接口  

105.    Enumeration list = NetworkInterface.getNetworkInterfaces();  

106.    while (list.hasMoreElements()) {  

107.        NetworkInterface iface = (NetworkInterface)list.nextElement();  

108.        System.out.println(iface.getDisplayName());  

109.        Enumeration addrs = iface.getInetAddresses();  

110.        while (addrs.hasMoreElements()) {  

111.            InetAddress addr = (InetAddress)addrs.nextElement();  

112.            System.out.println(addr);  

113.        }  

114.    }  

 

15. Java Mail

Java代碼 

1.    // 發送Mail  

2.    protected String msgRecIp = "[email protected]";  

3.    protected String msgSubject = "babytree";  

4.    protected String msgCc = "[email protected]";  

5.    protected String msgBody = "test body";  

6.    protected Session session;  

7.    protected Message msg;  

8.          

9.    public void doSend() {  

10.        // 創建屬性文件  

11.        Properties props = new Properties();  

12.        props.put("mail.smtp.host", "mailhost");  

13.        // 創建Session對象  

14.        session = Session.getDefaultInstance(props, null);  

15.        session.setDebug(true);  

16.        msg = new MimeMessage(session); // 創建郵件  

17.        msg. setFrom(new InternetAddress("[email protected]"));  

18.        InternetAddress toAddr = new InternetAddress(msgRecIp);  

19.        msg.addRecipient(Message.RecipientType.TO, toAddr);  

20.        InternetAddress ccAddr = new InternetAddress(msgCc);  

21.        msg.addRecipient(Message.RecipientType.CC, ccAddr);  

22.        msg.setSubject(msgSubject);  

23.        msg.setText(msgBody);   

24.        Transport.send(msg);   

25.    }  

26.      

27.    // 發送MIME郵件  

28.    Multipart mp = new MimeMultipart();  

29.    BodyPart textPart = new MimeBodyPart();  

30.    textPart.setText(message_body);  // 設置類型"text/plain"  

31.    BodyPart pixPart = new MimeBodyPart();  

32.    pixPart.setContent(html_data, "text/html");  

33.    mp.addBodyPart(textPart);  

34.    mp.addBodyPart(pixPart);  

35.    mesg.setContent(mp);  

36.    Transport.send(mesg);  

37.      

38.    // 讀Mail  

39.    Store store = session.getStore(protocol);  

40.    store.connect(host, user, password);  

41.    Folder rf;  

42.    rf = store.getFolder(root);  

43.    rf = store.getDefaultFolder();  

44.    rf.open(Folder.READ_WRITE);  

 

16. 數據庫訪問 

Java代碼 

1.    // JDO  

2.    Properties p = new Properties();  

3.    p.load(new FileInputStream("jdo.properties"));  

4.    PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(p);  

5.    PersistenceManager pm = pmf.getPersistenceManager();  

6.    // 提交數據  

7.    pm.currentTransaction().begin();  

8.    if (o instanceof Collection) {  

9.        pm.makePersistentAll((Collection) o);  

10.    } else {  

11.        pm.makePersistent(o);  

12.    }  

13.    pm.currentTransaction().commit();  

14.    pm.close();  

15.    // 取出數據  

16.    Object[] data = new Object[3];  

17.    pm.retrieveAll(data);  

18.    for (int i = 0; i < data.length; i++) {  

19.        System.out.println(data[i]);  

20.    }  

21.    pm.close();  

22.      

23.    // 數據操作  

24.    Class clz = Class.forName("oracle.jdbc.driver.OracleDriver");  

25.    String dbUrl = "jdbc:oracle:thin:@192.168.0.23:1521#:nms";  

26.    Connection conn = DriverManager.getConnection(dbUrl, "su", "1234");  

27.    Statement stmt = conn.createStatement();  

28.    ResultSet rs = stmt.executeQuery("select * from pmtable");  

29.    while (rs.next()) {  

30.        String name = rs.getString(1);  

31.        String otherName = rs.getString("name");  

32.    }  

33.      

34.    // 使用PreparedStatement提高性能,除了查詢,都使用executeUpdate執行操作   

35.    PreparedStatement pstmt = conn.prepareStatement("select * from pmtable where name = ?");  

36.    pstmt.setString(1, "sean");  

37.    ResultSet rs = pstmt.executeQuery();  

38.      

39.    // 調用存儲過程             

40.    CallableStatement cs = conn.prepareCall("{ call ListDefunctUsers }");  

41.    ResultSet rs = cs.executeQuery();  

42.              

43.    // 顯示數據庫表信息   

44.    DatabaseMetaData meta = conn.getMetaData();  

45.    meta.getDatabaseProductName();  

46.    meta.getDatabaseProductVersion();  

47.    meta.getDefaultTransactionIsolation();  

  

17. XML

    SAX: 在讀取文檔提取相應的標記事件(元素起始、元素結束、文檔起始)

    DOM: 在內存中構造與文檔中元素相應的樹,可以遍歷、搜索、修改

    DTD: 驗證文檔是否正確

    JAXP: 用於XML處理的Java API

    Castor: 開源項目,用於Java對象與XML映射

Java代碼 

1.    // 從對象中生成XML  

2.    private final static String FILENAME = "serial.xml";  

3.    public static void main(String[] args) throws IOException {  

4.        String a = "hard work and best callback";  

5.        new SerialDemoXML().write(a);  

6.        new SerialDemoXML().dump();  

7.    }  

8.    public void write(Object obj) throws IOException {  

9.        XMLEncoder os = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(FILENAME)));  

10.        os.writeObject(obj);  

11.        os.close();  

12.    }  

13.    public void dump() throws IOException {  

14.        XMLDecoder out = new XMLDecoder(new BufferedInputStream(new FileInputStream(FILENAME)));  

15.        System.out.println(out.readObject());  

16.        out.close();  

17.    }  

18.    serial.xml 格式內容如下:  

19.    <?xml version="1.0" encoding="UTF-8"?>   

20.    <java version="1.6.0_02" class="java.beans.XMLDecoder">   

21.        <string>hard work and best callback</string>   

22.    </java>  

23.    控 制臺輸出  

24.    hard work and best callback  

25.      

26.    // XSLT轉換XML  

27.    XSLT 可以用來對輸出格式進行各種控制  

28.    Transformer tx = TransformerFactory.newInstance().newTransformer(new StreamSource("people.xml"));  

29.    tx.transform(new StreamSource("people.xml"), new StreamResult("people.html"));  

30.      

31.    // 用SAX解析XML - 主要用於查找關鍵元素,不用全文遍歷  

32.    public SaxLister() throws SAXException, IOException {  

33.        XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");  

34.        parser.setContentHandler(new PeopleHandler());  

35.        parser.parse("C:\\StudySource\\javacooksrc2\\xml\\people.xml");  

36.    }  

37.    class PeopleHandler extends DefaultHandler {  

38.        boolean parent = false;  

39.        boolean kids = false;  

40.        public void startElement(String nsURI, String localName, String rawName, Attributes attr) throws SAXException {  

41.            System.out.println("startElement: " +  localName + "," + rawName);  

42.            if (rawName.equalsIgnoreCase("name"))  

43.                parent = true;  

44.            if (rawName.equalsIgnoreCase("children"))  

45.            kids = true;  

46.        }  

47.        public void characters(char[] ch, int start, int length) {  

48.            if (parent) {  

49.                System.out.println("Parent: " + new String(ch, start, length));  

50.                parent = false;  

51.            } else if (kids) {  

52.                System.out.println("Children: " + new String(ch, start, length));  

53.                kids = false;  

54.            }  

55.        }  

56.        public PeopleHandler() throws SAXException {  

57.            super();  

58.        }  

59.    }  

60.      

61.    // DOM解析XML - 遍歷整個樹  

62.    String uri = "file:" + new File("C:\\StudySource\\javacooksrc2\\xml\\people.xml").getAbsolutePath();  

63.    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  

64.    DocumentBuilder builder = factory.newDocumentBuilder();  

65.    Document doc = builder.parse(uri);  

66.    NodeList nodes = doc.getChildNodes();  

67.    for (int i = 0; i < nodes.getLength(); i++) {  

68.        Node n = nodes.item(i);  

69.        switch (n.getNodeType()) {  

70.        case Node.ELEMENT_NODE:  

71.            // todo  

72.            break;  

73.        case Node.TEXT_NODE:  

74.            // todo  

75.            break;  

76.        }  

77.    }  

78.      

79.    // 使用DTD或者XSD驗證  

80.    定 義好DTD或XSD文件  

81.    XmlDocument doc = XmlDocument.createXmlDocument(uri, true);  

82.      

83.    // 用DOM生成XML  

84.    DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();  

85.    DocumentBuilder parser = fact.newDocumentBuilder();  

86.    Document doc = parser.newDocument();  

87.    Node root = doc.createElement("Poem");  

88.    doc.appendChild(root);  

89.    Node stanza = doc.createElement("Stanza");  

90.    root.appendChild(stanza);  

91.    Node line = doc.createElement("Line");  

92.    stanza.appendChild(line);  

93.    line.appendChild(doc.createTextNode("Once, upon a midnight dreary"));  

94.    line = doc.createElement("Line");  

95.    stanza.appendChild(line);  

96.    line.appendChild(doc.createTextNode("While I pondered, weak and weary"));  

  

18. RMI

Java代碼 

1.    a. 定義 客戶端與服務器之間的通信接口  

2.    public interface RemoteDate extends Remote {  

3.        public Date getRemoteDate() throws RemoteException;  

4.        public final static String LOOKUPNAME = "RemoteDate";  

5.    }  

6.      

7.    b. 編 寫RMI服務器  

8.    public class RemoteDateImpl extends UnicastRemoteObject implements RemoteDate {  

9.        public RemoteDateImpl() throws RemoteException {  

10.            super();  

11.        }  

12.        public Date getRemoteDate() throws RemoteException {  

13.            return new Date();  

14.        }   

15.    }  

16.    RemoteDateImpl im = new RemoteDateImpl();  

17.    System.out.println("DateServer starting...");  

18.    Naming.rebind(RemoteDate.LOOKUPNAME, im);  

19.    System.out.println("DateServer ready.");  

20.      

21.    c. 運 行rmic生成stub  

22.    javac RemoteDateImpl.java  

23.    rmic RemoteDateImpl  

24.      

25.    d. 編 寫客戶端  

26.    netConn = (RemoteDate)Naming.lookup(RemoteDate.LOOKUPNAME);  

27.    Date today = netConn.getRemoteDate();  

28.    System.out.println(today.toString());  

29.      

30.    e. 確 保RMI註冊表運行  

31.    rmiregistry  

32.      

33.    f. 啓 動服務器  

34.    java RemoteDateImpl  

35.          

36.    g. 運 行客戶端  

37.    java DateClient  

  

19. 包和包裝機制

    jar cvf /tmp/test.jar .  // 當前目錄壓縮到test.jar中

    jar xvf /tmp/test.jar  // 把test.jar解壓到當前目錄

    從指定class運行jar文件

    a. Main-Class: HelloWord  // 注意中間有一個空格

    b. jar cvmf manifest.mf hello.jar HelloWorld.class

    c. java -jar hello.jar

 

20. Java線程

Java代碼 

1.    // 停止線程 - 不要使用stop()方法  

2.    private boolean done = false;  

3.    public void run() {  

4.        while (!done) {  

5.            //todo  

6.        }  

7.    }  

8.    public void shutDown() {  

9.        done = true;  

10.    }  

11.    可 以調用shutDown()方法來結束線程  

12.      

13.    // 如果讀取IO的時候出現堵塞,那麼可以使用下面方法  

14.    public void shutDown() throws IOException {  

15.        if (io != null)   

16.            io.close();  

17.    }  

18.      

19.    // 啓動一線程,等待控制檯輸入,使用join()方法來暫停當前線程,直到其他線程調用  

20.    Thread t = new Thread() {  

21.        public void run() {  

22.            System.out.println("Reading");  

23.            try {  

24.                System.in.read();  

25.            } catch (IOException e) {  

26.                System.err.println(e);  

27.            }  

28.            System.out.println("Thread finished.");  

29.        }  

30.    };  

31.    System.out.println("Starting");  

32.    t.start();  

33.    System.out.println("Joining");  

34.    try {  

35.        t.join();  

36.    } catch (InterruptedException e) {  

37.        System.out.println("Who dares imterrupt my sleep?");  

38.    }  

39.    System.out.println("Main finished.");  

40.      

41.    // 加鎖保證同步  

42.    Lock lock = new ReentrantLock();  

43.    try {  

44.        lock.lock();  

45.        // todo  

46.    } finally {  

47.        lock.unlock();     

48.    }  

49.      

50.    線 程通信wait(), notify(), notifyAll()  

51.    生產者-消費者模式  

52.    Executors  

  

21. 內省或“命令類的類”

Java代碼 

1.    // 反射  

2.    Class c = Class.forName("java.lang.String");  

3.    Constructor[] cons = c.getConstructors();  

4.    for (int i = 0; i < cons.length; i++) {  

5.        System.out.println(cons[i].toString());  

6.    }  

7.    Method[] meths = c.getMethods();  

8.    for (int i = 0; i < meths.length; i++) {  

9.        System.out.println(meths[i].toString());  

10.    }  

11.      

12.    // 動態裝載類  

13.    Class c = Class.forName("java.lang.String");  

14.    Object obj = c.newInstance();  

15.      

16.    // 通過反射調用類的方法  

17.    class X {  

18.        public void master(String s) {  

19.            System.out.println("Working on \"" + s + "\"");  

20.        }  

21.    }  

22.    Class clx = X.class;  

23.    Class[] argTypes = {String.class};  

24.    Method worker = clx.getMethod("master", argTypes);  

25.    Object[] theData = {"Chocolate chips"};  

26.    worker.invoke(new X(), theData);  

27.    輸 出: Working on "Chocolate chips"  

  

22. Java與其他語言的結合

Java代碼 

1.    // 執行CMD命令,在Eclipse控制檯輸出  

2.    Process p = Runtime.getRuntime().exec("C:/StudySource/ver.cmd");  

3.    p.waitFor(); // 等待命令執行完  

4.    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));  

5.    String s;  

6.    while ((s = br.readLine()) != null)  

7.        System.out.println(s);  

8.          

9.    // 調用Jython - 計算22.0/7  

10.    BSFManager manager = new BSFManager();  

11.    String[] fntypes = {".py"};  

12.    manager.registerScriptingEngine("jython", "org.apache.bsf.engines.jython.JythonEngine", fntypes);  

13.    Object r = manager.eval("jython", "testString", 0, 0, "22.0/7");  

14.    System.out.println("Result type is " + r.getClass().getName());  

15.    System.out.println("Result value is " + r);


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