创建文件并将其保存到动态存储

时间:2013-01-11 09:58:43

标签: java swing user-interface awt jfilechooser

我创建了一个这样的文件:

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

但我不想将文件保存在桌面上 - 我想打开另存为对话框,选择我要保存文件的位置。

我已经尝试了一些使用Frames的教程,但我不想创建任何框架,我想使用本机系统对话框。

2 个答案:

答案 0 :(得分:2)

  

..想要使用本机系统对话框。

你使用的是错误的语言。最接近的Java提供是使用原生PLAF的java.awt.FileDialogjavax.swing.JFileChooser

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);
    }
}

答案 1 :(得分:1)

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();
}