Runtime
Java可以通過Runtime來調用其他進程,如cmd命令,shell文件的執行等。可以應該該類設置系統時間,執行shell文件。此處記錄幾個有用應用如下。
設置本地時間
可以調用cmd /c date命令,完成本地時間設置,不過這個命令在win7下可以使用,但是win10需要管理員權限,可能無法設置系統時間。win7下使用Java實現修改本地時間代碼如下,需要注意的是waitFor是必須的,否則無法立即生效。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
/** * 設置本地日期 * @param date yyyy-MM-dd格式 */ private static void setSystemDate(String date){ String command1 = "cmd /c date " +date; System.out.println(command1); try { process = Runtime.getRuntime().exec(command1); //必須等待該進程結束,否則時間設置就無法生效 process.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } finally { if (process!= null ){ process.destroy(); } } } |
網卡吞吐量計算
可以通過cat /proc/net/dev命令獲取網卡信息,兩次獲取網卡發送和接收數據包的信息,來計算網卡吞吐量。實現如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
/** * @Purpose:采集網絡帶寬使用量 * @param args * @return float,網絡帶寬已使用量 */ public static Double getNetworkThoughput() { Double curRate = 0.0 ; Runtime r = Runtime.getRuntime(); // 第一次采集流量數據 long startTime = System.currentTimeMillis(); long total1 = calculateThoughout(r); // 休眠1秒后,再次收集 try { Thread.sleep( 1000 ); } catch (InterruptedException e) { e.printStackTrace(); } // 第二次采集流量數據 long endTime = System.currentTimeMillis(); long total2 = calculateThoughout(r); // 計算該段時間內的吞吐量:單位為Mbps(million bit per second) double interval = (endTime-startTime)/ 1000 ; curRate = (total2-total1)* 8 / 1000000 *interval; System.out.println( "收集網絡帶寬使用率結束,當前設備的網卡吞吐量為:" +(curRate)+ "Mbps." ); return curRate; } /** * 計算某個時刻網卡的收發數據總量 * @param runtime * @return */ private static long calculateThoughout(Runtime runtime){ Process process = null ; String command = "cat /proc/net/dev" ; BufferedReader reader = null ; String line = null ; long total = 0 ; try { process = runtime.exec(command); reader = new BufferedReader( new InputStreamReader(process.getInputStream())); while ((line = reader.readLine()) != null ) { line = line.trim(); // 考慮多網卡的情況 if (line.startsWith( "eth" )) { log.debug(line); line = line.substring( 5 ).trim(); String[] temp = line.split( "\\s+" ); total+=(Long.parseLong(temp[ 0 ].trim())); // Receive total+=(Long.parseLong(temp[ 8 ].trim())); // Transmit } } } catch (NumberFormatException | IOException e) { e.printStackTrace(); } finally { if (reader != null ) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (process != null ) { process.destroy(); } } return total; } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/wojiushiwo945you/article/details/53115189