java用GUI实现文件复制
时间: 2024-03-09 21:44:33 浏览: 11
以下是一个简单的 Java GUI 程序,可以实现文件复制功能:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class FileCopyGUI extends JFrame implements ActionListener {
private JTextField sourceField;
private JTextField destField;
private JButton copyButton;
public FileCopyGUI() {
super("文件复制");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(3, 1));
sourceField = new JTextField(20);
panel.add(sourceField);
destField = new JTextField(20);
panel.add(destField);
copyButton = new JButton("复制");
copyButton.addActionListener(this);
panel.add(copyButton);
setContentPane(panel);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == copyButton) {
String source = sourceField.getText();
String dest = destField.getText();
try {
FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
out.close();
JOptionPane.showMessageDialog(this, "复制完成!");
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "复制失败: " + ex.getMessage());
}
}
}
public static void main(String[] args) {
new FileCopyGUI();
}
}
```
这个程序创建了一个包含两个文本框和一个按钮的窗口,其中一个文本框用于输入源文件路径,另一个文本框用于输入目标文件路径。当用户单击“复制”按钮时,程序将尝试复制源文件到目标文件。
注意,此程序没有进行任何输入验证,因此可能会出现一些错误。例如,如果源文件路径不是一个有效的文件路径,程序将抛出 FileNotFoundException。