Runtime.getRuntime()是Java中的一个方法,用于获取当前运行时的Runtime对象。而getHostName()是InetAddress类的方法,用于获取当前主机的主机名。本文主要介绍Java中通过Runtime.getRuntime()和getHostName()获取主机名方法及示例代码。

1、通过Runtime.getRuntime().exec("hostname")获取主机名

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class GetHostNameUsingRuntime {
    public static void main(String[] args) {
        try {
            // 执行hostname命令
            Process hostnameProcess = Runtime.getRuntime().exec("hostname");

            // 获取命令的标准输出
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(hostnameProcess.getInputStream()));

            // 读取命令输出并打印到控制台
            String s;
            while ((s = stdInput.readLine()) != null) {
                System.out.println("主机名: " + s);
            }

            // 等待进程结束
            hostnameProcess.waitFor();

            // 获取命令的错误输出(如果有)
            BufferedReader stdError = new BufferedReader(new InputStreamReader(hostnameProcess.getErrorStream()));
            while ((s = stdError.readLine()) != null) {
                System.err.println("错误信息: " + s);
            }

        } catch (IOException e) {
            System.err.println("IOException发生: " + e.getMessage());
        } catch (InterruptedException e) {
            System.err.println("InterruptedException发生: " + e.getMessage());
        }
    }
}

2、通过getHostName()方法获取主机名

import java.net.InetAddress;  
import java.net.UnknownHostException;  
import java.util.Properties;  
import java.util.Set;  
  
  
public class TestSystemProperties {  
  
    public static void main(String [] args){  
        InetAddress netAddress = getInetAddress();  
        System.out.println("host ip:" + getHostIp(netAddress));  
        System.out.println("host name:" + getHostName(netAddress));  
        Properties properties = System.getProperties();  
        Set<String> set = properties.stringPropertyNames(); //获取java虚拟机和系统的信息。  
        for(String name : set){  
            System.out.println(name + ":" + properties.getProperty(name));  
        }  
    }  
  
    public static InetAddress getInetAddress(){  
  
        try{  
            return InetAddress.getLocalHost();  
        }catch(UnknownHostException e){  
            System.out.println("unknown host!");  
        }  
        return null;  
  
    }  
  
    public static String getHostIp(InetAddress netAddress){  
        if(null == netAddress){  
            return null;  
        }  
        String ip = netAddress.getHostAddress(); //get the ip address  
        return ip;  
    }  
  
    public static String getHostName(InetAddress netAddress){  
        if(null == netAddress){  
            return null;  
        }  
        String name = netAddress.getHostName(); //get the host address  
        return name;  
    }  
  
}