How to save something to the desktop without hard-coding the directory?

前端 未结 3 1253
再見小時候
再見小時候 2020-12-19 07:14

I was wondering how to get java to save a text file named hello.txt to the desktop without writing

\"C:\\\\Users\\\\Austin\\\\Desktop\"
         


        
相关标签:
3条回答
  • 2020-12-19 08:12

    User.home works, but just hardcoding the directory should be just fine.

    0 讨论(0)
  • 2020-12-19 08:14
    import java.io.File;
    
    class FindDesktopOnWindows {
    
        public static void main(String[] args) throws Exception {
            if (System.getProperty("os.name").toLowerCase().indexOf("win")<0) {
                System.err.println("Sorry, Windows only!");
                System.exit(1);
            }
            File desktopDir = new File(System.getProperty("user.home"), "Desktop");
            System.out.println(desktopDir.getPath() + " " + desktopDir.exists());
    
            java.awt.Desktop.getDesktop().open(desktopDir);
        }
    }
    

    I forgot different Locales. Very fragile code (even for code that starts out OS specific). See my comment below re. OS X/JFileChooser.

    ..how the (System.getProperty("user.home"), "Desktop") works..

    Oracle helpfully provides docs for this kind of thing.

    See System.getProperty(String) & new File(String,String).


    I'll cede to an expert (or a user) on this, but I don't think OS X supports any application icons or document icons directly on the ..start screen, default look, whatever.. Probably better to offer the end user a JFileChooser pointing to user.home and ask them to save the document to the desktop (or wherever they feel like).

    0 讨论(0)
  • 2020-12-19 08:19

    This points you on desktop dir:

    javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory()
    
    0 讨论(0)
提交回复
热议问题