java经典代码及注释_22个Java经典实例 带完美注释

1. 获取环境变量

Java代码

1.    System.getenv("

titter.gifATH");

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 hm = new HashMap();

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

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

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

32.    // 方法1: 获取全部键值

33.    Iterator 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 myList = new ArrayList();

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);

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);

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 = "hxydream@163.com";

3.    protected String msgSubject = "babytree";

4.    protected String msgCc = "nobody@erewhon.com";

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("nobody@host.domain"));

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);

20.    }

21.    pm.close();

22.

23.    // 数据操作

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

25.    String dbUrl = "jdbc

shocked.gifracle:thin

huffy.gif192.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.   

21.        hard work and best callback

22.   

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("

titter.gifarent: " + 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("

titter.gifoem");  

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.toString());

6.    }

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

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

9.        System.out.println(meths.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);

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值