从Windows XP和Windows 7的“我的文档”访问文件时出错

先生,我正在一个Java应用程序。在那个应用程序,我必须从“我的文档”访问文件。 问题是随着Windows版本,当我使用的Windows 7,它可以作为“文件”文件夹访问,但对于Windows XP的是“我的文档”。

我正在写下面的代码来访问Windows 7中“文档”文件夹中的文件。

public static void main(String[] arr) { try { String source = System.getProperty("user.home")+ File.separator + "Documents"; File[] Files = new File(source).listFiles(); System.out.println(Files.length); } catch(Exception ex) { ex.printStackTrace(); } } 

和Windows Xp

  public static void main(String[] arr) { try { String source = System.getProperty("user.home")+ File.separator + "My Documents"; File[] Files = new File(source).listFiles(); System.out.println(Files.length); } catch(Exception ex) { ex.printStackTrace(); } } 

请你能为我推荐一个通用的方法,可以应用于所有版本的Windows?

您可以检查操作系统版本,然后使用它来映射正确的文件名。

没有标准的Java方法,但存在多个库,例如Winfoldersjava 。

不要简单地猜测和追加“我的文档”。 您将遇到本地化版本的Windows的问题。 例如在挪威语中,名称是“Mine dokumenter”,而不是“我的文档”。

检查Apache的公共项目 。 有一个类SystemUtils提供有关系统的更多信息。