簡體   English   中英

將File對象寫入另一個位置

[英]Writing File object to another location

我選擇了使用

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

也看看這個問題: 如何使用JFileChooser保存文件? #MightBeHelpfull

Swing只會為您提供位置/文件對象。 您將必須自己編寫新文件。

要復制文件,我將指出以下問題: 用Java復制文件的標准簡潔方法?

將文件讀入InputStream ,然后將其寫出到OutputStream

如果使用的是JDK 1.7,則可以使用java.nio.file.Files類,該類提供了幾種將文件復制到給定目的地的復制方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM