Developer
Developer

Reputation: 11

Operating System Log in and log out time using java

Can any one help me to know how to detect system log in and log off time using java api? Only login time when logging in and logout time when system shutdown. If possible is der available for linux machine also.

Upvotes: 1

Views: 1408

Answers (2)

Dima
Dima

Reputation: 8662

take a look at this:

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;
}

this will give you the uptime, so subtract it from current time.

Upvotes: 2

DeadlyJesus
DeadlyJesus

Reputation: 1533

If by system you mean the Operating System, then i'll sugest you to use a script for that, especially for linux. For example you can use the file ~/.bashrc to detect the log in.

Upvotes: 0

Related Questions