【问题标题】:Save Any format file using JFileChooser in Swing在 Swing 中使用 JFileChooser 保存任何格式文件
【发布时间】:2016-08-08 17:30:53
【问题描述】:

我使用JFileChooser 打开了一个文件。现在我还想将该文件保存在JFileChooser 的计算机目录中。如何保存?

目前我的代码只是提供 UI,但没有保存功能。

package javaapplication1;

import java.awt.image.RenderedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author KHAN
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Browse");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Save to");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(55, 55, 55)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE)
                    .addComponent(jTextField1))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(jButton2)))
                .addContainerGap(56, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(87, 87, 87)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addComponent(jButton2)))
                .addContainerGap(123, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JFileChooser chooser = new JFileChooser();

        if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(null)) {
            File file = chooser.getSelectedFile();
            file.getAbsoluteFile();
        }

    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JFileChooser chooser=new JFileChooser();
        FileFilter filter=new FileNameExtensionFilter("JPEG file", "jpg" , "jpeg" , "pdf" , "txt" ,"png");
        chooser.showOpenDialog(null);
        File f=chooser.getSelectedFile();
        String filename=f.getAbsolutePath();
        jTextField1.setText(filename);
        jTextField2.setText(filename);

    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
          NewJFrame sfc = new NewJFrame();
    sfc.setVisible(true);

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration                   
}

//Eddited

 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JFileChooser chooser = new JFileChooser();

        if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(null)) {
            File file = chooser.getSelectedFile();
            file.getAbsoluteFile();
        }

    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JFileChooser chooser=new JFileChooser();
        FileFilter filter=new FileNameExtensionFilter("JPEG file", "jpg" , "jpeg" , "pdf" , "txt" ,"png");
        chooser.showOpenDialog(null);
        File f=chooser.getSelectedFile();
        String filename=f.getAbsolutePath();
        jTextField1.setText(filename);
        jTextField2.setText(filename);

    }      

【问题讨论】:

  • 具体保存什么文件?是文本、结构化文本、图像……?
  • 兄弟我刚刚点击浏览按钮,从桌面我选择 example.pdf 或 example.png 。现在我有另一个另存为按钮。现在点击保存,因为我想将它保存到 PC 的任何目录
  • 我已经编辑了代码,请看编辑部分。第一个功能是浏览文件。第二个功能会将浏览的文件保存到任何目录。 (另存为窗口)。它可以是任何格式。目前第二个功能只显示另存为窗口,但它不保存
  • 1) 我不是你的“兄弟”。我也不是你的'cuz'。我来这个网站不是为了交朋友,这就是FB的用途。 2) 我希望通过更正第一个代码示例,你会得到提示,但由于那没有发生.. 请对代码和代码 sn-ps、结构化文档(如 HTML)使用 代码格式 /XML 或输入/输出。为此,选择文本并单击消息发布/编辑表单顶部的{} 按钮。 3) “我已编辑代码” 嗯。 。 好的。我在下面的回答中有哪些部分无法回答您的问题? 试试看!
  • 我仍然面临问题。请您在我的功能中编辑并发布它

标签: java image swing file-io jfilechooser


【解决方案1】:

您似乎想保存图像。为此,请使用ImageIO.write(RenderedImage,String,File):

使用支持给定格式的任意ImageWriter 将图像写入File。如果已经存在File,则其内容将被丢弃。

【讨论】:

    【解决方案2】:

    你必须自己写。见FileOutputStreamJava NIO

    【讨论】:

    • 你可以在这里添加这些行吗?
    • 您想将什么“保存”到文件中?
    • 查看stackoverflow.com/questions/2885173/… 看看是否对您有帮助。如果没有,请告诉我您要保存到文件中的内容
    • 兄弟我刚刚点击浏览按钮,从桌面我选择 example.pdf 或 example.png 。现在我有另一个另存为按钮。现在点击保存,因为我想将它保存到 PC 的任何目录
    • 如果您只想复制之前选择的文件,请参阅docs.oracle.com/javase/7/docs/api/java/nio/file/… 您可以从 java.io.File.toPath() 方法中获取 java.nio.file.Path
    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多