如何在 Java 中将字符串拆分为多个子字符串
问题描述
如何将字符串拆分为多个子字符串?
解决方案
以下示例显示如何借助 net.InetAddress 类的 InetAddress.getByName() 方法将主机名更改为其特定的 IP 地址。
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetIP {
public static void main(String[] args) {
InetAddress address = null;
try {
address = InetAddress.getByName("www.javatutorial.com");
} catch (UnknownHostException e) {
System.exit(2);
}
System.out.println(address.getHostName() + "=" + address.getHostAddress());
System.exit(0);
}
}
结果
上述代码示例将产生以下结果。
http://www.javatutorial.com = 123.14.2.35
以下是 Java 中 getHostAddress() 和 getHostName() 的另一个示例
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Demo {
public static void main(String[] args) {
InetAddress ipadd;
String hostname;
try {
ipadd = InetAddress.getLocalHost();
hostname = ipadd.getHostName();
System.out.println("Your IP address : " + ipadd);
System.out.println("Your Hostname : " + hostname);
} catch (UnknownHostException e) {
}
}
}
上述代码示例将产生以下结果。
Your IP address : 4d623edc62d4/172.17.0.2 Your Hostname : 4d623edc62d4
java_networking.html

