Reputation: 3
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.");
}
Upvotes: 0
Views: 161
Reputation: 2224
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
Upvotes: 2