我想开发的JSF页面,可以显示交换大小,如果操作系统是Linux和什么百分比被利用。我发现可以从/proc/swaps中读取此信息。但当我打开它的时候,我得到了这个
Filename Type Size Used Priority
/dev/sda2 partition 2047992 0 -1我如何才能得到这些值- 2047992和0?我知道如何阅读文本文件的内容。例如:
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (IOException e) {
}另一个更高级的问题是,如果我有两个交换怎么办?
问候
发布于 2012-03-24 05:24:40
如果你决定解析这个文件,这里有一个实现...
Pattern pattern = Pattern.compile("([\\/A-Za-z0-9]+)[\\s]+([a-z]+)[\\s]+([0-9]+)[\\s]+([0-9]+)[\\s]+([\\-0-9]+).*");
BufferedReader reader = new BufferedReader(new FileReader("/proc/swaps"));
String s = reader.readLine();
while (s!= null){
Matcher matcher = pattern.matcher(s);
if (matcher.matches()){
System.out.println(s);
System.out.println(matcher.group(3));
System.out.println(matcher.group(4));
}
s = reader.readLine();
}
reader.close();发布于 2012-03-24 04:49:01
(特定于Linux的)系统调用sysinfo(struct sysinfo* info)使用以下内容填充info:
struct sysinfo {
long uptime; /* Seconds since boot */
unsigned long loads[3]; /* 1, 5, and 15 minute load averages */
unsigned long totalram; /* Total usable main memory size */
unsigned long freeram; /* Available memory size */
unsigned long sharedram; /* Amount of shared memory */
unsigned long bufferram; /* Memory used by buffers */
unsigned long totalswap; /* Total swap space size */
unsigned long freeswap; /* swap space still available */
unsigned short procs; /* Number of current processes */
unsigned long totalhigh; /* Total high memory size */
unsigned long freehigh; /* Available high memory size */
unsigned int mem_unit; /* Memory unit size in bytes */
char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding for libc5 */
};其中totalswap和freeswap可能就是你要找的。
我不知道您是如何在Java语言中进行本机平台调用的,但是对于您自己解析/proc/swaps文件来说,这是一个很好的选择。
编辑:
我在JNA上玩了一下,想出了这个:
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Structure;
import com.sun.jna.NativeLong;
public class Test {
public interface CStdLib extends Library {
static class SysInfo extends Structure {
public NativeLong uptime;
public NativeLong[] loads = new NativeLong[3];
public NativeLong totalram;
public NativeLong freeram;
public NativeLong sharedram;
public NativeLong bufferram;
public NativeLong totalswap;
public NativeLong freeswap;
public short procs;
public NativeLong totalhigh;
public NativeLong freehigh;
public int mem_unit;
/* some padding? */
}
int sysinfo(SysInfo info);
}
public static void main(String[] args) {
CStdLib c = (CStdLib)Native.loadLibrary("c", CStdLib.class);
CStdLib.SysInfo s = new CStdLib.SysInfo();
c.sysinfo(s);
System.out.println("totalram: " + s.totalram);
}
}不幸的是,对于带符号的long来说,您可能会遇到值太大的问题,因此在Java语言中可能会得到错误的值,这是我在尝试读取机器上的交换值时看到的。
希望这能有所帮助!(注意:我从来没有和Java程序员:)混淆过)
https://stackoverflow.com/questions/9845868
复制相似问题