Java常见问题汇总
生活随笔
收集整理的這篇文章主要介紹了
Java常见问题汇总
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
來源: StackOverflow, 自己使用中總結
集合
并發
網絡
獲取本機IP
InetAddress inetAddress = InetAddress.getLocalHost(); String host = inetAddress.getHostAddress(); System.out.print("host is " + host + "\n");結果: host is 127.0.0.1
在linux環境下,沒法獲取正確的ip地址,當然也有一部分人碰巧獲取了正確的結果。實際上這個函數是按照host來查找ip地址的,在linux中這些地址在/etc/hosts文件中:
127.0.0.1 localhost 127.0.0.1 ubuntu # The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters因此程序里也只是讀取了該文件下的ip地址,用戶的網絡如果是靜態ip的話,自己手動設置一下,也能返回正確的IP地址,但是這么做的確是很麻煩。還有一個方法就是,執行ifconfig,解析對應的結果。
或者使用NetworkInterface接口來獲取:
public static String getHostIp() {Enumeration<NetworkInterface> netInterfaces = null;String host = "";try {netInterfaces = NetworkInterface.getNetworkInterfaces();while (netInterfaces.hasMoreElements()) {NetworkInterface ni = netInterfaces.nextElement();if(!ni.getName().isEmpty()) {Enumeration<InetAddress> ips = ni.getInetAddresses();while (ips.hasMoreElements()) {InetAddress inetAddress = ips.nextElement();host = inetAddress.getHostAddress();log.info("IP:" + host);if(inetAddress.getHostAddress().matches("\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|$)){4}\\b")) {return host;}}}}} catch (Exception e) {if(log.isInfoEnabled()) {log.info(e.getMessage());}}return host;}其他
package-info.java作用
為標注在包上Annotation提供便利;
聲明友好類和包常量;
提供包的整體注釋說明。
示例說明:
總結
以上是生活随笔為你收集整理的Java常见问题汇总的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++拷贝对象
- 下一篇: 解决visual studio已安装的问