-1

I had open a file using JFileChooser. Now I also want to save that file in a computer directory by JFileChooser. How can I save it?

Currently my code is just providing UI but it doesn't have saving functionality.

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

    }      
Asim Khan
  • 1
  • 3
  • Save what file specifically? Is it text, structured text, an image..? – Andrew Thompson Aug 09 '16 at 00:43
  • Bro I had just click on browse button , from Desktop I choose example.pdf or example.png . Now I had other button of Save As.Now by clicking save as i want to save it to any directory of PC – Asim Khan Aug 09 '16 at 11:13
  • I had edit the code , kindly see the edit portion.First function is browsing the file.And second fuction will save that broswed file to any directory. (Save As Windows).It can be of any format.Currently second fuction just shows Save as windows but it does not save – Asim Khan Aug 09 '16 at 11:31
  • 1) I'm not your 'bro'. I'm not your 'cuz' either. I don't come to this site to make friends, that's what FB is for. 2) I hoped that by correcting the first code sample, you'd take the hint, but since that did not happen.. Please use **code formatting** for code and code snippets, structured documents like HTML/XML or input/output. To do that, **select the text and click the `{}` button at the top of the message posting/editing form.** 3) *"I had edit the code"* Umm.. OK. And what part of what my answer below fails to answer your question? ***Try it!*** – Andrew Thompson Aug 09 '16 at 11:34
  • I am still facing problem.can you please edit it in my function and post it – Asim Khan Aug 09 '16 at 11:44
  • *"I am still facing problem..."* When you're facing problems & fail to even ***try*** doing what people suggest, you won't solve the problem. SO is not a help desk, it's not a code generation machine. – Andrew Thompson Aug 09 '16 at 12:59

2 Answers2

1

It seems you want to save an image. For that, use ImageIO.write(RenderedImage,String,File):

Writes an image using an arbitrary ImageWriter that supports the given format to a File. If there is already a File present, its contents are discarded.

Andrew Thompson
  • 163,965
  • 36
  • 203
  • 405
0

You have to write to it yourself. See FileOutputStream and Java NIO

Jayfray
  • 417
  • 3
  • 12
  • Can you Add those lines here? – Asim Khan Aug 08 '16 at 18:24
  • What do you want to 'save' to the file? – Jayfray Aug 08 '16 at 18:54
  • Check out http://stackoverflow.com/questions/2885173/how-to-create-a-file-and-write-to-a-file-in-java see if that helps you. If not then tell me what you want to save to the file – Jayfray Aug 08 '16 at 18:55
  • Bro I had just click on browse button , from Desktop I choose example.pdf or example.png . Now I had other button of Save As.Now by clicking save as i want to save it to any directory of PC – Asim Khan Aug 08 '16 at 18:59
  • If all you want to do is copy the file you pick before then see https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy(java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...) You can get the java.nio.file.Path from the java.io.File.toPath() method – Jayfray Aug 08 '16 at 22:01