7

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.... :(

PulsePanda
  • 1,806
  • 10
  • 33
  • 56

3 Answers3

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • alright, explain how the `(System.getProperty("user.home"), "Desktop")` works please? – PulsePanda Apr 15 '12 at 22:23
  • alright. so i cant find how to make the jfilechooser... and so could u give an example on just the basics? like just creating a jframe, but make this pop up, and make it be able to save? – PulsePanda Apr 15 '12 at 22:30
  • well, im trying to do this for free. its for a school project – PulsePanda Apr 15 '12 at 22:33
  • 2
    +1 for `suggesting JFileChooser`. On Mac OS X, the `user.home` property yields the correct path. "Desktop" is a valid directory name, even if it's been [localized](http://apple.stackexchange.com/a/37237/20589). – trashgod Apr 16 '12 at 00:45
3

This points you on desktop dir:

javax.swing.filechooser.FileSystemView.getFileSystemView().getHomeDirectory()
mauretto
  • 3,183
  • 3
  • 27
  • 28
0

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

Hock3yPlayer
  • 2,531
  • 2
  • 14
  • 9