读取文件时出现java.nio.file.AccessDeniedException异常

3
我想使用这段代码读取文件内容:
String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));

在一些系统中,该文件可能不存在或为空。我该如何捕获这个异常?当找不到文件且没有值时,我想打印出“无文件”的信息。


使用try-catch (http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html)。 - MrTux
3个回答

2
AccessDeniedException 只会在使用 新的文件 API 时抛出。 使用 inputStream 从源文件中打开流,以便您可以捕获该异常。

尝试以下代码:

try 
 {
  final InputStream in = new Files.newInputStream(Path.get("/sys/devices/virtual/dmi/id/chassis_serial"));
 } catch (FileNotFoundException ex) {
   System.out.print("File not found");
 } catch(AccessDeniedException e) {
   System.out.print("File access denied");
 }

0

尝试使用过滤器file.canRead())来避免任何访问异常。


-1
创建一个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");
}

阅读MrTux建议的try catch块这里,以及java File和java io 这里


5
邪恶,邪恶,邪恶。不要捕获“Exception”!只需捕获您预期会抛出的异常即可。 - Stephen C
1
存在性检查只是浪费时间。打开文件本来就会做这件事。 - user207421
你说得完全正确,Stephen C。我的try/catch答案是懒惰的典范。 - laazer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接