King Luy
King Luy

Reputation: 141

Create file and save it to an dynamic storage

I create a file like this:

PrintWriter out = new PrintWriter(
                     new FileOutputStream(
                      new File("C:/Users/.../Desktop/Server Recipe Log.txt"), 
                      true));
             out.println("serverText");
             out.close();

But I don't want to save the file on my desktop - I want to open the save as dialog to choose the place where I want to save the file.

I have tried out some tutorials with Frames but I don't want to create any frame, I want to use the native system dialog.

Upvotes: 0

Views: 376

Answers (2)

daredesm
daredesm

Reputation: 615

JFileChooser jl = new JFileChooser();
jl.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int save = jl.showSaveDialog(null);
if (JFileChooser.APPROVE_OPTION == save){
PrintWriter out = new PrintWriter(
                 new FileOutputStream(
                  new File(jl.getSelectedFile().getAbsolutePath()+"/name.txt"), 
                  true));
         out.println("serverText");
         out.close();
}

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168845

..want to use the native system dialog.

You are using the wrong language. The closest Java offers is a java.awt.FileDialog or a javax.swing.JFileChooser using the native PLAF.

E.G.

import java.awt.*;
import javax.swing.*;

class FileDialogs {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                FileDialog fd = new FileDialog((Frame)null);
                fd.setVisible(true);
                
                JFileChooser fc = new JFileChooser();
                fc.showSaveDialog(null);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}

Upvotes: 2

Related Questions