3

I was trying to create a program to read a CSV file from the downloads folder on any windows computer and could not get the Java BufferedReader to find the file.

I read that java can handle absolute paths so I did:

File f = new File("%systemdrive%\\users\\%username%\\Downloads\\quotes.csv");
BufferedReader br = new BufferedReader(new FileReader(f));

This threw an IOException with the message :

 %systemdrive%\users\%username%\Downloads\quotes.csv (The system cannot find the path specified)

I made sure that this file existed by entering the same path into File Explorer and easily enough, the file showed up.

I was wondering if something like this is possible and if there is some way to find and read this file.

Thank you for any help!

Mehul Raheja
  • 127
  • 1
  • 7

2 Answers2

4

The %systemdrive% and %username% appear to be environment variables expanded by the File Explorer.

You might find this other entry in SO ( How to find out operating system drive using java? ) interesting to get the value for %systemdrive. Similarly, you can apply the same call to System.getenv to get the username.

FWIW, here there's a list of environment variables in Windows. Note the %HOMEPATH% environment variable, which points to the home directory of the current user.

With all these premises, you might consider the following code to fix your issue:

String userhome = System.getenv ("HOMEPATH");
File f = new File(userhome + "\\Downloads\\quotes.csv");
BufferedReader br = new BufferedReader(new FileReader(f));
Community
  • 1
  • 1
Harald
  • 3,110
  • 1
  • 24
  • 35
2

You could try something like this:

String userHome = System.getProperty("user.home");
String path = userHome + "\\Downloads\\quotes.csv";
File f = new File(path);
BufferedReader br = new BufferedReader(new FileReader(f));
  • 1
    Even better use a system-independent path separator variable: `String pathSeparator = File.separator; String path = userHome + pathSeparator + "Downloads" + pathSeparator + "quotes.csv";` – JD9999 Aug 25 '16 at 20:26