简体   繁体   English

在Java中的用户目录上创建文件

[英]Creating a file on User directory in Java

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. 假设我的用户名是ThisPC,如果我这样写:“ C:\\ Users \\ ThisPC \\ Desktop \\ Lista Produse.txt”,它将按预期工作,将文件保存在桌面上,但是当我尝试使用%USERNAME%时,它是不工作。 (Keep in mind I'm using Java) Thank you in advance for your help. (请记住,我在使用Java)预先感谢您的帮助。

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.");
    }

Your first problem is that Java has no reason to parse the path that you supply, it is not a windows command shell. 您的第一个问题是Java没有理由解析您提供的路径,它不是Windows命令外壳程序。 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. 但是,这仍然很危险,因为Windows上的用户目录可以位于不同的位置,也可以没有完整的用户名。 see In java under Windows, how do I find a redirected Desktop folder? 请参见在Windows下的Java中,如何找到重定向的桌面文件夹?

For a more detailed option, that will be more reliable, look into this How to get the Desktop path in java 有关更详细的选择,它将更加可靠,请查看此如何在Java中获取桌面路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM