检测java.io.FileNotFoundException的根本原因

Dan*_*ler 13 java file-permissions localization 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)
Run Code Online (Sandbox Code Playgroud)

上面的示例显示德国Windows抱怨用户名或密码无效.

有没有办法解析异常消息,以获得有关异常发生原因的更精细的信息?消息解析的问题在于,在不同的语言环境中,消息会有所不同.

Ale*_*yak 10

在创建之前自己检查文件是否存在/读写权限FileOutputStream.

File test_csv = new File( "\\server\share\directory\test.csv" );

if ( test_csv.exists( ) && test_csv.canWrite( ) )
{
  // Create file writer
  ...
}
else
{
  // notify user
  ...
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果需要创建新文件,有时您必须检查目标文件父级的读/写权限.

File test_csv = new File( "\\server\share\directory\test.csv" );
File parent_dir = test_csv.getParentFile( )

if ( parent_dir.exists( ) && parent_dir.canWrite( ) )
{
  // Create file writer
  ...
}
else
{
  // notify user
  ...
}
Run Code Online (Sandbox Code Playgroud)