jinlin
2025-03-01 86f02fee03614fef275c6e0c355d73318ca3025e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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(); // 删除临时文件
        }
    }
}