【问题标题】:Writing File object to another location将文件对象写入另一个位置
【发布时间】:2012-04-27 15:00:58
【问题描述】:

我已使用

选择文件
File file = fileChooser.getSelectedFile();

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

【问题讨论】:

标签: java swing


【解决方案1】:

要选择您需要的文件,例如,

    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

【讨论】:

    【解决方案2】:

    Swing 只会为您提供位置/文件对象。您将不得不自己编写新文件。

    要复制文件,我会指出这个问题:Standard concise way to copy a file in Java?

    【讨论】:

      【解决方案3】:

      如果您使用的是 JDK 1.7,则可以使用 java.nio.file.Files 类,它提供了多种复制方法来将文件复制到给定的目标。

      【讨论】:

        【解决方案4】:

        将文件读入InputStream,然后将其写入OutputStream

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多