简体   繁体   中英

Full path of saved file in Java

I want to get the full path of the file that the user saved in Java. Here is the code of the method save and it works okay but actually i need to get the path that the user had save his file in. Could someone help me:

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

public class FileChooserSave {
    private static void createAndShowUI() {
        final JFileChooser chooser = new JFileChooser(new File(".")) {
            public void approveSelection() {
                if (getSelectedFile().exists()) {
                    int n = JOptionPane.showConfirmDialog(this, "Do You Want to Overwrite File?", "Confirm Overwrite",
                            JOptionPane.YES_NO_OPTION);

                    if (n == JOptionPane.YES_OPTION)
                        super.approveSelection();

                } else
                    super.approveSelection();
            }
        };

        chooser.setSelectedFile(new File(""));
        int returnVal = chooser.showSaveDialog(null);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println(chooser.getSelectedFile());
        }
    }
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

您可以使用以下方法获取绝对路径:

myFileChooser.getSelectedFile().getAbsolutePath()

Here is a sample of java code for absolute path from JFileChoose

JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");   
 
int userSelection = fileChooser.showSaveDialog(parentFrame);
 
if (userSelection == JFileChooser.APPROVE_OPTION) {
    File fileToSave = fileChooser.getSelectedFile();
    System.out.println("Save as file: " + fileToSave.getAbsolutePath());
}

hope it helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM