Last post show a Python version to get CPU frequency, and the post in my another blog show a Android version. Here is a Java SE version.
JavaRead_scaling_cur_freq.java
package javaread_scaling_cur_freq;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
public class JavaRead_scaling_cur_freq {
public static void main(String[] args) {
readCpuFreqNow();
}
static private void readCpuFreqNow() {
File[] cpuFiles = getCPUs();
System.out.println("number of cpu: " + cpuFiles.length);
for (File cpuFile : cpuFiles) {
String path_scaling_cur_freq
= cpuFile.getAbsolutePath() + "/cpufreq/scaling_cur_freq";
System.out.println(path_scaling_cur_freq);
System.out.println(cmdCat(path_scaling_cur_freq));
}
}
//run Linux command
//$ cat f
static private String cmdCat(String path){
StringBuilder stringBuilder = new StringBuilder();
Process process;
try {
process = Runtime.getRuntime().exec("cat " + path);
process.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine())!= null) {
stringBuilder.append(line).append("\n");
}
} catch (IOException | InterruptedException ex) {
Logger.getLogger(JavaRead_scaling_cur_freq.class
.getName()).log(Level.SEVERE, null, ex);
}
return stringBuilder.toString();
}
/*
* Get file list of the pattern
* /sys/devices/system/cpu/cpu[0..9]
*/
static private File[] getCPUs() {
class CpuFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return Pattern.matches("cpu[0-9]+", pathname.getName());
}
}
File dir = new File("/sys/devices/system/cpu/");
File[] files = dir.listFiles(new CpuFilter());
return files;
}
}
This video show the code build on Raspberry Pi 2 using NetBeans IDE.
The code work on other Linux also, such as Ubuntu. This video show the jar build on Raspberry Pi 2, copy to Ubuntu Linux and run directly.
Related:
- Install NetBeans IDE on Raspberry Pi 2/Raspbian, to program using Java