2013-04-24 92 views
0

任何人都可以幫助我 知道 如何使用java api檢測系統登錄和註銷時間? 登錄時只有登錄時間和系統關機時的登出時間。 如果可能的話,也可用於Linux機器。操作系統使用java登錄和註銷時間

+2

您的意思是操作系統或應用程序。 – shazin 2013-04-24 09:31:41

回答

0

如果你的系統指的是操作系統,那麼我會要求你使用這個腳本, ,特別是對於linux。例如,你可以使用文件〜/ .bashrc中檢測到日誌中

1

在此看一看:

public static long getSystemUptime() throws Exception { 
long uptime = -1; 
String os = System.getProperty("os.name").toLowerCase(); 
if (os.contains("win")) { 
    Process uptimeProc = Runtime.getRuntime().exec("net stats srv"); 
    BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream())); 
    String line; 
    while ((line = in.readLine()) != null) { 
     if (line.startsWith("Statistics since")) { 
      SimpleDateFormat format = new SimpleDateFormat("'Statistics since' MM/dd/yyyy hh:mm:ss a"); 
      Date boottime = format.parse(line); 
      uptime = System.currentTimeMillis() - boottime.getTime(); 
      break; 
     } 
    } 
} else if (os.contains("mac") || os.contains("nix") || os.contains("nux") || os.contains("aix")) { 
    Process uptimeProc = Runtime.getRuntime().exec("uptime"); 
    BufferedReader in = new BufferedReader(new InputStreamReader(uptimeProc.getInputStream())); 
    String line = in.readLine(); 
    if (line != null) { 
     Pattern parse = Pattern.compile("((\\d+) days,)? (\\d+):(\\d+)"); 
     Matcher matcher = parse.matcher(line); 
     if (matcher.find()) { 
      String _days = matcher.group(2); 
      String _hours = matcher.group(3); 
      String _minutes = matcher.group(4); 
      int days = _days != null ? Integer.parseInt(_days) : 0; 
      int hours = _hours != null ? Integer.parseInt(_hours) : 0; 
      int minutes = _minutes != null ? Integer.parseInt(_minutes) : 0; 
      uptime = (minutes * 60000) + (hours * 60000 * 60) + (days * 6000 * 60 * 24); 
     } 
    } 
} 
return uptime; 
} 

這會給你的正常運行時間,所以從當前時間減去它。