バッテリ残量プログラム(Java版)
昨日ブログに書いたバッテリー容量残量表示HaskellプログラムをJavaで書いてみた。
基本的に、Ubuntuでは、
$ cat /proc/acpi/battery/BAT0/info
present: yes
design capacity: 74880 mWh
last full capacity: 73830 mWh
battery technology: rechargeable
design voltage: 14400 mV
design capacity warning: 3691 mWh
design capacity low: 200 mWh
cycle count: 0
capacity granularity 1: 1 mWh
capacity granularity 2: 1 mWh
model number: 42T4776
serial number: 2141
battery type: LION
OEM info: SONY
のように表示されるのを利用している。
package battery;
public class Bat {
public static int getNumber(final String ptn, final BufferedReader state) throws IOException {
for(String s = state.readLine(); s != null; s = state.readLine()){
Matcher m = Pattern.compile(ptn + "\\s*(\\d+).*").matcher(s);
if(m.matches()) return Integer.parseInt(m.group(1));
}
return -1;
}
public static int getCapacitence(String path, String ptn){
BufferedReader state = null;
int result = -1;
try {
state = new BufferedReader(new FileReader(path));
result = getNumber(ptn,state);
state.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
int full = getCapacitence("/proc/acpi/battery/BAT0/info", "last full capacity:");
int now = getCapacitence("/proc/acpi/battery/BAT0/state", "remaining capacity:");
System.out.format("%.0f%%%n", now * 100.0 / full);
}
}
やっぱり、Javaは冗長過ぎて嫌になる。