package com.example.server.utils;
|
|
import com.example.Application;
|
|
import javax.swing.*;
|
import java.io.*;
|
import java.nio.file.Files;
|
import java.nio.file.StandardCopyOption;
|
|
public class DownLoadTmpFile {
|
public static void down(String name,JFrame frame1){
|
name = "templateFile/" + name;
|
InputStream inputStream = Application.class.getClassLoader().getResourceAsStream(name);
|
|
if (inputStream == null) {
|
try {
|
inputStream = new FileInputStream(name);
|
} catch (FileNotFoundException e) {
|
e.printStackTrace();
|
}
|
}
|
|
// 创建临时文件
|
File tempFile;
|
try {
|
tempFile = File.createTempFile("tmp", ".tmp");
|
tempFile.deleteOnExit(); // 确保临时文件在程序退出时删除
|
Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
} catch (IOException e) {
|
JOptionPane.showMessageDialog(frame1, "无法创建临时文件: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
|
return;
|
}
|
|
// 弹出文件选择对话框
|
JFileChooser fileChooser = new JFileChooser();
|
fileChooser.setSelectedFile(new File(name)); // 默认文件名
|
int result = fileChooser.showSaveDialog(frame1);
|
|
if (result == JFileChooser.APPROVE_OPTION) {
|
File selectedFile = fileChooser.getSelectedFile();
|
try {
|
// 将临时文件复制到用户选择的位置
|
Files.copy(tempFile.toPath(), selectedFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
JOptionPane.showMessageDialog(frame1, "文件下载成功", "成功", JOptionPane.INFORMATION_MESSAGE);
|
} catch (IOException e) {
|
JOptionPane.showMessageDialog(frame1, "文件保存失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
|
}
|
} else {
|
// 如果用户取消操作,不显示额外提示
|
tempFile.delete(); // 删除临时文件
|
}
|
}
|
}
|