我认为这只适用于英语Windows安装:
System.getProperty("user.home") + "/Desktop";
Run Code Online (Sandbox Code Playgroud)
如何让这个非英语Windows工作?
我试图了解Java在创建File对象时解析相对路径的方式.
使用的操作系统:Windows
对于下面的代码片段,我得到一个,IOException因为它找不到路径:
@Test
public void testPathConversion() {
File f = new File("test/test.txt");
try {
f.createNewFile();
System.out.println(f.getPath());
System.out.println(f.getAbsolutePath());
System.out.println(f.getCanonicalPath());
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
我的理解是,Java将提供的路径视为绝对路径,并在路径不存在时返回错误.所以这很有道理.
当我更新上面的代码以使用相对路径时:
@Test
public void testPathConversion() {
File f = new File("test/../test.txt");
try {
f.createNewFile();
System.out.println(f.getPath());
System.out.println(f.getAbsolutePath());
System.out.println(f.getCanonicalPath());
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
它创建一个新文件并提供以下输出:
test\..\test.txt
C:\JavaForTesters\test\..\test.txt
C:\JavaForTesters\test.txt
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我的假设是,即使提供的路径不存在,因为路径包含"/../",java将其视为相对路径并在其中创建文件user.dir.所以这也是有道理的.
但如果我更新相对路径如下:
@Test
public void testPathConversion() {
File f = new File("test/../../test.txt");
try {
f.createNewFile();
System.out.println(f.getPath());
System.out.println(f.getAbsolutePath()); …Run Code Online (Sandbox Code Playgroud) 我有这个程序,它将输出一个文本文件并将其保存在用户的计算机中,我想将它保存在桌面上,因为这是每个人都有的路径.
我目前正在使用Windows 8进行编码,我应该使用哪条路径来保证它在Windows 7上保存到桌面?
File file = new File("C:/Users/Wil/Downloads/Dropbox/abc.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
JOptionPane.showMessageDialog(null,"Receipt Saved!");
Run Code Online (Sandbox Code Playgroud)