gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:36:18 28 4
gpt4 key购买 nike

我想使用此代码读取文件内容:

String content = new String(Files.readAllBytes(Paths.get("/sys/devices/virtual/dmi/id/chassis_serial")));

在某些系统上此文件不存在或为空。我如何捕捉这个异常?我想在没有文件且没有值时打印消息“无文件”。

最佳答案

只有在使用新文件 API 时才会抛出AccessDeniedException。使用 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");
}

关于读取文件时出现 java.nio.file.AccessDeniedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25349182/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com