我选择了使用

File file = fileChooser.getSelectedFile();


现在,我想在用户单击“保存”按钮时将用户选择的文件写入另一个位置。如何使用秋千实现?

最佳答案

要选择文件,您需要类似的内容,

    JFileChooser open = new JFileChooser();
    open.showOpenDialog(this);
    selected = open.getSelectedFile().getAbsolutePath(); //selected is a String


...并保存副本,

    JFileChooser save = new JFileChooser();
    save.showSaveDialog(this);
    save.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    tosave = fileChooser.getSelectedFile().getAbsolutePath(); //tosave is a String

    new CopyFile(selected,tosave);


... copyFile类将类似于

public class CopyFile {

    public CopyFile(String srFile, String dtFile) {

        try {
            File f1 = new File(srFile);
            File f2 = new File(dtFile);
            InputStream in = new FileInputStream(f1);

            OutputStream out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            System.out.println("File copied.");
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage() + " in the specified directory.");
            System.exit(0);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}




也看看这个问题:How to save file using JFileChooser? #MightBeHelpfull

08-28 17:30