0

My code is posted below. Let's say my username is ThisPC, if I write like this: "C:\Users\ThisPC\Desktop\Lista Produse.txt" it is working as intended, saving my file on desktop, but when I try with %USERNAME% it is not working. (Keep in mind I'm using Java) Thank you in advance for your help.

try{ File f=new File("C:\\Users\\%USERNAME%\\Desktop\\List.txt"); Formatter x; x=new Formatter("C:\\Users\\%USERNAME%\\Desktop\\List.txt"); while(enALL.hasMoreElements()){ x.format(""+enALL.nextElement()); x.format("\r\n"); } x.close(); } catch(FileNotFoundException e){ JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, "Error."); } 
1
  • I assume you're working Java Commented Dec 2, 2017 at 11:39

1 Answer 1

2

Your first problem is that Java has no reason to parse the path that you supply, it is not a windows command shell. To get the current username, try

String username = System.getProperty("user.name"); 

and substitute it in.

However, this is still dangerous, as user directories on Windows can be located in different places, or without the full user name. see In java under Windows, how do I find a redirected Desktop folder?

For a more detailed option, that will be more reliable, look into this How to get the Desktop path in java

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.