集册 Java实例教程 从shell命令获取Mac地址

从shell命令获取Mac地址

欢马劈雪     最近更新时间:2020-01-02 10:19:05

740
从shell命令获取Mac地址


//package com.nowjava;

import java.io.BufferedReader;
/** 
 来自 N o w J a v a . c o m - 时代Java**/

import java.io.IOException;

import java.io.InputStreamReader;


public class Main {



    public static String getMacAddr(String commond, String newLine) {

        if (commond == null)

            return "Bad Commond!";

        String os = getOSName();

        if (os.startsWith("windows")) {

            return Window(commond, newLine);

        } else {

            return Linux(commond, newLine);

        }

    }
/*来自 N o  w  J a v a . c o m - 时  代  Java*/

    private static String getOSName() {

        return System.getProperty("os.name").toLowerCase();

    }


    private static String Window(String commond, String newLine) {

        BufferedReader bufferedReader = null;

        Process process = null;

        try {

            process = Runtime.getRuntime().exec(commond);  

            bufferedReader = new BufferedReader(new InputStreamReader(

                    process.getInputStream()));

            String line = null;

            StringBuffer tmp = new StringBuffer();

            while ((line = bufferedReader.readLine()) != null) {

                tmp.append(line).append(newLine);

            }

            return tmp.toString();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                if (bufferedReader != null) {

                    bufferedReader.close();

                }

            } catch (IOException e1) {

                e1.printStackTrace();

            }

            bufferedReader = null;

            process = null;

        }

        return "Bad Commond!";

    }


    private static String Linux(String commond, String newLine) {

        BufferedReader bufferedReader = null;

        Process process = null;

        try {

            process = Runtime.getRuntime().exec(commond);

            bufferedReader = new BufferedReader(new InputStreamReader(

                    process.getInputStream()));

            String line = null;

            StringBuffer tmp = new StringBuffer();

            while ((line = bufferedReader.readLine()) != null) {

                tmp.append(line).append(newLine);

            }

            
展开阅读全文