本範例使用 Swing 建立圖形介面,透過 JFileChooser 選擇來源檔案與目標資料夾,點擊「copy」按鈕執行檔案複製。核心複製邏輯封裝於 Copy 類別,使用 FileInputStream/FileOutputStream 配合 1KB 緩衝區進行位元組流複製。
// 主視窗類別 CopyFile (繼承 JFrame)
package test2;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
public class CopyFile extends JFrame {
private JPanel jContentPane;
private JButton jButton, jButton1, jButton2;
private JTextField jTextField, jTextField1;
public CopyFile() { super(); initialize(); }
private void initialize() {
this.setSize(300, 200);
this.setContentPane(getJContentPane());
}
// ... 介面元件初始化程式碼省略(含 JFileChooser 選檔/選資料夾邏輯) ...
// 複製按鈕事件:
// String from = jTextField.getText();
// String to = jTextField1.getText();
// Copy copy1 = new Copy();
// boolean copy_ok = copy1.copy(from, to);
}
// 複製工具類別
package test2;
import java.io.*;
public class Copy {
public boolean copy(String file1, String file2) {
try {
File file_in = new File(file1);
File file_out = new File(file2);
FileInputStream in1 = new FileInputStream(file_in);
FileOutputStream out1 = new FileOutputStream(file_out);
byte[] bytes = new byte[1024];
int c;
while ((c = in1.read(bytes)) != -1)
out1.write(bytes, 0, c);
in1.close();
out1.close();
return true;
} catch (Exception e) {
System.out.println("Error!");
return false;
}
}
}
介面包含:來源檔案輸入框、目標資料夾輸入框、選檔按鈕、選資料夾按鈕、複製執行按鈕。複製成功在控制台輸出「copy is successful!」,失敗輸出「copy is failture!」。