我是Java新手,我想使用Java阅读此文件内容:
Filename Type Size Used Priority
/dev/mapper/VolGroup00-LogVol01 partition 524280 0 -1
/dev/mapper/VolGroup00-LogVol02 partition 324280 0 -1
你能告诉我一些Java 8的工作示例吗?
这是到目前为止的代码:
private static HashMap<String, HashMap<String, Long>> totalSwap() throws FileNotFoundException, IOException
{
File file = new File("/proc/swaps");
if (!file.exists())
{
System.err.println("/proc/swaps did not exist!");
return null;
}
else if (file.isDirectory())
{
System.err.println("/proc/swaps is a directory, not a file.");
return null;
}
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())
{
HashMap<String, Long> usageData2 = new HashMap<>();
usageData2.put("allSwap", Long.parseLong(matcher.group(3)));
usageData2.put("utilizedSwap", Long.parseLong(matcher.group(4)));
data.put("First", usageData2);
}
s = reader.readLine();
}
reader.close();
return data;
}
我不知道如何阅读FileName列。最后我想得到这个结果:
HashMap</dev/mapper/VolGroup00-LogVol01, HashMap<Size, 524280>
HashMap<Used, 0>>
HashMap</dev/mapper/VolGroup00-LogVol02, HashMap<Size, 334220>
HashMap<Used, 0>>
你能帮忙解决这个问题吗?
答案 0 :(得分:1)
最好使用制表符分隔符进行拆分,如果我没记错的话,linux正在使用制表符输出。
我不得不使用你的代码进行即兴创作,但重新插入代码应该很容易。
请参阅下面的示例:
private static HashMap<String, HashMap<String, Long>> totalSwap()
{
HashMap<String, HashMap<String, Long>> data = new HashMap<String, HashMap<String, Long>>();
Pattern pattern = Pattern.compile("([\\/A-Za-z0-9]+)[\\s]+[A-Za-z]+[\\s]+([0-9]+)[\\s]+([0-9]+)[\\s]+([\\-0-9]+).*");
String s = "/dev/mapper/VolGroup00-LogVol01\tpartition\t524280\t0\t-1\n/dev/mapper/VolGroup00-LogVol02\tpartition\t324280\t0\t-1";
String[] columns = s.split("\t");
for (String line : columns) {
HashMap<String, Long> usageData2 = new HashMap<>();
usageData2.put("allSwap", Long.parseLong(columns[2]));
usageData2.put("utilizedSwap", Long.parseLong(columns[3]));
data.put(columns[0], usageData2);
}
return data;
}
答案 1 :(得分:0)
也许最好将StringTokenizer与分隔符选项卡(&#34; \ t&#34;)一起使用并检索所需的列。