Error accessing file from My Documents for Windows Xp and Windows 7

Sir, I work in a Java application. In this application, I have to access files from My Documents. The problem occurs with the version of Windows, when I use Windows 7, it can be obtained in the Documents folder, but for Windows XP it is My Documents.

I am writing the following code to access files from the Documents folder in 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(); } } 

and for 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(); } } 

Please, can you offer me a general method that can be applied to all versions of Windows?

+7
java windows version
source share
3 answers

You can check the version of the operating system and then use it to match the correct file name.

+1
source share

There is no standard Java method for this, but there are several libraries, for example Winfoldersjava .

Don't just guess and add My Documents. You will have problems with localized versions of Windows. For example, in Norwegian, the name is Mine dokumenter, not My Documents.

0
source share

Check out the apache commons project . There is a SystemUtils class that provides more information about the system.

0
source share

All Articles