Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

Any help would be great. so like:

FileWriter fileWriter = new FileWriter(fileName.getText(), true);

..and the fileName.getText() is just going to be the 'hello'.

UPDATE: i think that i would be able to use the jfilechooser, so would this work?

JFileChooser chooser = new JFileChooser();
chooser.setVisible(true);

would that work? and if so, how would i get it to save the file using the selection in there? im a noob.... :(

like image 979
PulsePanda Avatar asked Apr 15 '12 21:04

PulsePanda


People also ask

Where save on desktop?

On Windows computers, most of the files you work on are saved to the C: drive, which is the default drive. To save to another drive (e.g., flash drive), you would need to know the drive letter and specify that drive letter when saving the file.

How do I save a folder to the same time?

This works for me: Press F12 (the default shortcut for the Save As dialog box). It opens the folder where the current document is stored, instead of the default local file location stored in the Options > Save dialog.

Where to save files in laptop?

Most computers will automatically save your data to the hard drive, usually known as the C drive. This is the most common place to store files.


1 Answers

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).

like image 132
Andrew Thompson Avatar answered Sep 30 '22 01:09

Andrew Thompson