Java 怎么在Linux上获取主机名

2019年7月19日20:23:36Java 怎么在Linux上获取主机名已关闭评论 464 862字阅读2分52秒

1.简介

Java 怎么在Linux上获取主机名?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Main{
    static public String getHostname() {
        return sysExec("/bin/hostname");
    }
    static public String sysExec(String command) {
        String result = new String();
        try {
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec(command);
            
            InputStream inputstream = proc.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(
                    inputstream);
            BufferedReader bufferedreader = new BufferedReader(
                    inputstreamreader);
            
            String line;
            while ((line = bufferedreader.readLine()) != null) {
                result += line;
                result += "\n";
            }
            
            try {
                if (proc.waitFor() != 0) {
                    System.err.println("exit value = " + proc.exitValue());
                }
            } catch (InterruptedException e) {
                System.err.println(e);
                throw new SystemUtilitiesException();
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return result;
    }
}

 
继续阅读
编程十万个怎么办