Java File Copy Application: Simple File Copying using Byte Streams
import java.awt.; import java.awt.event.; import javax.swing.; import java.io.;
public class FileCopyApplication extends JFrame implements ActionListener { private JTextArea sourceTextArea; private JTextArea destinationTextArea; private JButton copyButton;
public FileCopyApplication() {
setTitle('File Copy Application');
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建源文件文本区域
sourceTextArea = new JTextArea();
JScrollPane sourceScrollPane = new JScrollPane(sourceTextArea);
sourceScrollPane.setBorder(BorderFactory.createTitledBorder('Source File'));
// 创建目标文件文本区域
destinationTextArea = new JTextArea();
JScrollPane destinationScrollPane = new JScrollPane(destinationTextArea);
destinationScrollPane.setBorder(BorderFactory.createTitledBorder('Destination File'));
// 创建复制按钮
copyButton = new JButton('Copy');
copyButton.addActionListener(this);
// 创建容器并设置布局管理器
Container container = getContentPane();
container.setLayout(new BorderLayout());
container.add(sourceScrollPane, BorderLayout.CENTER);
container.add(destinationScrollPane, BorderLayout.EAST);
container.add(copyButton, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == copyButton) {
String sourceText = sourceTextArea.getText();
String destinationText = destinationTextArea.getText();
try (InputStream inputStream = new FileInputStream(sourceText);
OutputStream outputStream = new FileOutputStream(destinationText)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
JOptionPane.showMessageDialog(this, 'File copied successfully.');
} catch (IOException e) {
JOptionPane.showMessageDialog(this, 'An error occurred while copying the file.');
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
FileCopyApplication application = new FileCopyApplication();
application.setVisible(true);
}
});
}
}
原文地址: https://www.cveoy.top/t/topic/fOOC 著作权归作者所有。请勿转载和采集!