检测 java.io.FileNotFoundException 的根本原因
FileNotFoundException 会在各种场合抛出 - 不一定仅当文件名无效时,而且当权限不允许创建或读取文件时也会抛出:
java.io.FileNotFoundException: \\server\share\directory\test.csv (Anmeldung fehlgeschlagen: unbekannter Benutzername oder falsches Kennwort)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:179)
at java.io.FileOutputStream.<init>(FileOutputStream.java:131)
at java.io.FileWriter.<init>(FileWriter.java:73)
上面的示例显示德国 Windows 抱怨用户名或密码无效。
有没有办法通过解析异常消息来获取有关异常发生的具体原因的更细粒度的信息?消息解析的问题在于,在不同的区域设置中,消息会有所不同。
FileNotFoundException is thrown on all sorts of occasions - not necessarily only when the file name is invalid, but also when e. g. permissions do not allow a file to be created or read:
java.io.FileNotFoundException: \\server\share\directory\test.csv (Anmeldung fehlgeschlagen: unbekannter Benutzername oder falsches Kennwort)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:179)
at java.io.FileOutputStream.<init>(FileOutputStream.java:131)
at java.io.FileWriter.<init>(FileWriter.java:73)
The above example shows a German Windows complaining about invalid username or password.
Is there a way short of parsing the exceptions message to get a little finer grained information on why exactly the exception occurred? Problem with message parsing is that in different locales the messages will vary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在创建
FileOutputStream
之前,请自行检查文件存在/读写权限。请注意,如果需要创建新文件,有时您必须检查目标文件父级的读/写权限。
Do the check for file existence/read-write permissions yourself before creating
FileOutputStream
.Notice that sometimes you will have to check the read/write permissions on a parent of you destination file, if you need to create a new file.
您可能想使用 java.io.File 对象,然后尝试读取文件。有一个 canRead 方法,您可以使用它来确定用户是否可以读取该文件。
You may want to look at the properties of the file using the java.io.File object before attempting to read the file. There's a canRead method on that you can use to determine whether or not the user can read the file.
一种方法是查看异常的实际类型:正如您可以从 docs,有很多子类提供更细粒度的信息。
然而,你可能不会走得太远。与大多数已检查的异常一样,通常最好记录/报告异常并询问用户如何纠正它的选择。
One approach is to look at the actual type of the exception: as you can see from the docs, there are a lot of subclasses that provide finer-grained information.
However, you probably won't get far with that. As with most checked exceptions, it's usually better to log/report the exception and ask the user for choices on how to correct it.