Java swing 点击按钮复制文件到程序运行的当前目录
时间: 2024-03-01 22:51:23 浏览: 24
您可以使用以下代码实现:
```java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class FileCopy extends JFrame implements ActionListener {
private JButton button;
private JPanel panel;
public FileCopy() {
super("文件复制");
this.setSize(300, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
button = new JButton("选择文件");
button.addActionListener(this);
panel.add(button);
this.add(panel);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("选择文件");
int result = chooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File source = chooser.getSelectedFile();
File dest = new File(source.getName());
try (FileChannel sourceChannel = new FileInputStream(source).getChannel();
FileChannel destChannel = new FileOutputStream(dest).getChannel()) {
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
JOptionPane.showMessageDialog(this, "文件复制成功!");
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "文件复制失败!");
}
}
}
public static void main(String[] args) {
new FileCopy();
}
}
```
该程序创建了一个窗口,并在其中添加了一个按钮,当用户点击按钮时,会弹出一个文件选择对话框,用户可以选择需要复制的文件。程序会将该文件复制到程序运行的当前目录,并提示用户操作结果。