相关疑难解决方法(0)

如何在java中获取桌面路径

我认为这只适用于英语Windows安装:

System.getProperty("user.home") + "/Desktop";
Run Code Online (Sandbox Code Playgroud)

如何让这个非英语Windows工作?

java desktop

57
推荐指数
5
解决办法
8万
查看次数

Java如何解析新File()中的相对路径?

我试图了解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)

java file relative-path

40
推荐指数
4
解决办法
13万
查看次数

文件输出Java的桌面路径

我有这个程序,它将输出一个文本文件并将其保存在用户的计算机中,我想将它保存在桌面上,因为这是每个人都有的路径.

我目前正在使用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)

java desktop

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

java ×3

desktop ×2

file ×1

relative-path ×1