我使用此代码来读取 Linux SWAP 空间:
public void getSwap() throws FileNotFoundException, IOException
{
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();
}
我想修改代码,当没有文件/proc/swaps时返回null。我不想在文件丢失时中断代码。
最佳答案
您可以非常轻松地创建一个文件对象,并在创建缓冲读取器之前使用 .exists() 方法检查其是否存在(及其 isDirectory() 方法以确保它不是目录)。
然后,如果它不存在,您可以采取任何您想要的操作。
响应您的代码请求:我没有尝试编译它,但它应该像这样工作:
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;
}
您还应该将函数包装在 try { } catch() {}
中,并使用注释处理异常,因为您事先检查了存在性,因此该异常不会发生。这样您就不必声明该函数抛出已检查的异常。
关于Java 代码中的 java.io.FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25370513/