我想使用以下代码读取文件内容:
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
在某些系统中,该文件不存在或为空。我是怎么发现这个异常的?当没有文件和没有值时,我想打印消息"No“。
发布于 2014-08-17 12:53:48
创建一个File
对象并检查它是否存在。如果是这样,那么将该文件转换为字节数组并检查大小是否大于0是安全的。如果是将其转换为字符串。我在下面添加了一些示例代码。
File myFile = new File("/sys/devices/virtual/dmi/id/chassis_serial");
byte[] fileBytes;
String content = "";
if(myFile.exists()) {
fileBytes = File.readAllBytes(myfile.toPath);
if(fileBytes.length > 0) content = new String(fileBytes);
else System.out.println("No file");
else System.out.println("No file");
我知道这不是你要找的那个班轮。另一种选择就是直接做
try {
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));
} catch(Exception e) {
System.out.print("No file exists");
}
https://stackoverflow.com/questions/25349182
复制相似问题