hbx 23 часов назад
Родитель
Сommit
d17a20cc43

+ 16 - 2
src/com/mes/component/MesWebView.java

@@ -13,7 +13,8 @@ import java.util.Date;
 
 public class MesWebView extends JFXPanel {
 
-    public static WebEngine engine = null;
+    // 每个页面持有自己的 WebEngine,换工位后只刷新本页面
+    private WebEngine engine = null;
 
     public MesWebView(String url){
 
@@ -38,7 +39,20 @@ public class MesWebView extends JFXPanel {
         });
     }
 
+    /** 用新URL重新加载页面(换工位/换用户后调用)。 */
+    public void loadUrl(final String url){
+        Platform.runLater(() -> {
+            if (engine != null) {
+                engine.load(url);
+            }
+        });
+    }
+
     public void reloadWeb(){
-        engine.reload();
+        Platform.runLater(() -> {
+            if (engine != null) {
+                engine.reload();
+            }
+        });
     }
 }

+ 9 - 40
src/com/mes/ui/DataUtil.java

@@ -2,6 +2,7 @@ package com.mes.ui;
 
 import com.alibaba.fastjson2.JSONObject;
 import com.mes.netty.NettyClient;
+import com.mes.util.ConfigUtil;
 import com.mes.util.DateLocalUtils;
 import com.mes.util.JdbcUtils;
 
@@ -136,11 +137,7 @@ public class DataUtil {
             String msgType = "MQDW";
             String craft = "100000";
             String params = "";
-            String enconding = "UTF-8";
-            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
-            Properties pro = new Properties();
-            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
-            pro.load(br);
+            Properties pro = ConfigUtil.loadProperties();
             String gw = "GW"+rightPad(pro.getProperty("mes.gw"), 8);
             String start = "aaaabbbbbABW";
             String gy = "GY" + rightPad(craft, 6);
@@ -161,11 +158,7 @@ public class DataUtil {
 
     public static Boolean sendMessage(NettyClient nettyClient,String msgType,String craft,String lx,String sn,String result,String user,String paramNums,String params){
         try{
-            String enconding = "UTF-8";
-            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
-            Properties pro = new Properties();
-            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
-            pro.load(br);
+            Properties pro = ConfigUtil.loadProperties();
             String gw = "GW"+rightPad(pro.getProperty("mes.gw"), 8);
             String start = "aaaabbbbbABW";
             String gy = "GY" + rightPad(craft, 6);
@@ -199,11 +192,7 @@ public class DataUtil {
 
     public static JSONObject getBindMaterail() {
         try{
-            String enconding = "UTF-8";
-            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
-            Properties pro = new Properties();
-            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
-            pro.load(br);
+            Properties pro = ConfigUtil.loadProperties();
             String mes_server_ip = pro.getProperty("mes.server_ip");
             String oprno = pro.getProperty("mes.gw").trim();
             String lineSn = pro.getProperty("mes.line_sn").trim();
@@ -225,11 +214,7 @@ public class DataUtil {
 
     public static JSONObject saveBindMaterail(String batchSn,String craft,String materialId,String type) {
         try{
-            String enconding = "UTF-8";
-            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
-            Properties pro = new Properties();
-            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
-            pro.load(br);
+            Properties pro = ConfigUtil.loadProperties();
             String mes_server_ip = pro.getProperty("mes.server_ip");
             String oprno = pro.getProperty("mes.gw").trim();
             String lineSn = pro.getProperty("mes.line_sn").trim();
@@ -252,11 +237,7 @@ public class DataUtil {
     // 新增:上传工件ld点击记录,NG时调用
     public static JSONObject ldResult(String sn, String userCode,String ldFlag) {
         try{
-            String enconding = "UTF-8";
-            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
-            Properties pro = new Properties();
-            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
-            pro.load(br);
+            Properties pro = ConfigUtil.loadProperties();
 
             String mes_server_ip = pro.getProperty("mes.server_ip");
             String oprno = pro.getProperty("mes.gw").trim();
@@ -293,11 +274,7 @@ public class DataUtil {
 
     public static JSONObject pcResult(String sn, String userCode,String ldFlag,String result,int isRepair) {
         try{
-            String enconding = "UTF-8";
-            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
-            Properties pro = new Properties();
-            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
-            pro.load(br);
+            Properties pro = ConfigUtil.loadProperties();
 
             String mes_server_ip = pro.getProperty("mes.server_ip");
             String oprno = pro.getProperty("mes.gw").trim();
@@ -338,11 +315,7 @@ public class DataUtil {
 
     public static JSONObject pcCheck(String sn, String userCode,int isRepair) {
         try{
-            String enconding = "UTF-8";
-            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
-            Properties pro = new Properties();
-            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
-            pro.load(br);
+            Properties pro = ConfigUtil.loadProperties();
 
             String mes_server_ip = pro.getProperty("mes.server_ip");
             String oprno = pro.getProperty("mes.gw").trim();
@@ -457,11 +430,7 @@ public class DataUtil {
     public static WorkRecordResp getWorkRecordList(String oprno, String sn, int pageNo, int pageSize) {
         WorkRecordResp resp = new WorkRecordResp();
         try {
-            String enconding = "UTF-8";
-            InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
-            Properties pro = new Properties();
-            BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
-            pro.load(br);
+            Properties pro = ConfigUtil.loadProperties();
             String mes_server_ip = pro.getProperty("mes.server_ip");
             String lineSn = pro.getProperty("mes.line_sn").trim();
 

+ 5 - 2
src/com/mes/ui/LoginFarme.java

@@ -195,11 +195,14 @@ public class LoginFarme extends JFrame {
 //                        MesClient.indexPanelB.add(MesClient.jfxPanel);
 //                    }
 
+                    String checkUrl = "http://"+ MesClient.mes_server_ip+":8980/js/a/mes/mesProcessCheckRecord/ulist?ucode="+user_id+"&oprno="+MesClient.mes_gw+"&lineSn="+MesClient.mes_line_sn+"&__sid="+MesClient.sessionid;
                     if(MesClient.jfxPanel2 == null){
-                        String url = "http://"+ MesClient.mes_server_ip+":8980/js/a/mes/mesProcessCheckRecord/ulist?ucode="+user_id+"&oprno="+MesClient.mes_gw+"&lineSn="+MesClient.mes_line_sn+"&__sid="+MesClient.sessionid;
-                        MesClient.jfxPanel2 = new MesWebView(url);
+                        MesClient.jfxPanel2 = new MesWebView(checkUrl);
                         MesClient.jfxPanel2.setSize(990, 550);
                         MesClient.indexPanelC.add(MesClient.jfxPanel2);
+                    }else{
+                        // 换工位/换用户后重新登录,按当前工位和会话刷新开班点检页面
+                        MesClient.jfxPanel2.loadUrl(checkUrl);
                     }
 
                     MesClient.initWarehouseData();

+ 215 - 8
src/com/mes/ui/MesClient.java

@@ -5,6 +5,7 @@ import com.mes.component.MesRadio;
 import com.mes.component.MesWebView;
 import com.mes.netty.NettyClient;
 import com.mes.netty.ProtocolParam;
+import com.mes.util.ConfigUtil;
 import com.mes.util.DateLocalUtils;
 import com.mes.util.ErrorMsg;
 import com.mes.util.HttpUtils;
@@ -71,6 +72,16 @@ public class MesClient extends JFrame {
     public static JButton status_menu;
     public static JButton user_menu;
 
+    // 隐藏入口:双击「心跳」值后再双击「登录用户」值,设置菜单出现「更改工位」
+    private static JMenuItem changeStationMenu;
+    private static boolean stationGestureHeartClicked = false;
+    private static long stationGestureHeartAt = 0L;
+    private static final long STATION_GESTURE_TIMEOUT_MS = 15000L;
+
+    public static JLabel gwLabel; // 顶部工位号/名称
+    public static JTabbedPane workRecordTabbedPane;
+    public static WorkRecordPanel workRecordPanelCurrent;
+
     public static int scan_type = 0;
     public static JButton finish_ok_bt;
     public static JButton finish_ng_bt;
@@ -136,13 +147,9 @@ public class MesClient extends JFrame {
         }
     }
 
-    //读配置文件
+    //读配置文件(外部 config/config.properties 优先,其次 jar 内置)
     private static void readProperty() throws IOException{
-        String enconding = "UTF-8";
-        InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
-        Properties pro = new Properties();
-        BufferedReader br = new BufferedReader(new InputStreamReader(is, enconding));
-        pro.load(br);
+        Properties pro = ConfigUtil.loadProperties();
         mes_gw =  pro.getProperty("mes.gw");
         mes_server_ip = pro.getProperty("mes.server_ip");
         mes_tcp_port = Integer.parseInt(pro.getProperty("mes.tcp_port"));
@@ -394,7 +401,7 @@ public class MesClient extends JFrame {
         setJMenuBar(menuBar);
 
         // 左侧:工位号和名称
-        JLabel gwLabel = new JLabel("工位:" + mes_gw + " - " + mes_gw_des);
+        gwLabel = new JLabel("工位:" + mes_gw + " - " + mes_gw_des);
         gwLabel.setFont(new Font("微软雅黑", Font.BOLD, 22));
         gwLabel.setForeground(new Color(0, 102, 204));
         gwLabel.setBorder(new EmptyBorder(0, 10, 0, 20));
@@ -467,6 +474,18 @@ public class MesClient extends JFrame {
         });
         settingMenu.add(resetTcpMenu_1);
 
+        // 默认隐藏;双击「心跳」→ 双击「登录用户」后出现
+        changeStationMenu = new JMenuItem("更改工位");
+        changeStationMenu.setIcon(new ImageIcon(MesClient.class.getResource("/bg/menu_setting.png")));
+        changeStationMenu.setFont(new Font("微软雅黑", Font.PLAIN, 20));
+        changeStationMenu.setVisible(false);
+        changeStationMenu.addActionListener(new ActionListener() {
+            public void actionPerformed(ActionEvent e) {
+                showChangeStationDialog();
+            }
+        });
+        settingMenu.add(changeStationMenu);
+
         contentPane = new JPanel();
         contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
         setContentPane(contentPane);
@@ -527,6 +546,12 @@ public class MesClient extends JFrame {
         user_menu.setBackground(Color.BLACK);
         toolBar.add(user_menu);
 
+        // 隐藏解锁入口:心跳(文字/值)双击,然后登录用户(文字/值)双击
+        bindStationGesture(heart_beat_status_label, true);
+        bindStationGesture(heart_beat_menu, true);
+        bindStationGesture(user_status_label, false);
+        bindStationGesture(user_menu, false);
+
         JLabel space_3 = new JLabel("    ");
         toolBar.add(space_3);
 
@@ -754,7 +779,7 @@ public class MesClient extends JFrame {
         // tabbedPane.addTab("工作记录", new ImageIcon(MesClient.class.getResource("/bg/menu_data_preprocess.png")), searchScrollPane, null);
 
         // 创建工作记录的子 TabbedPane
-        JTabbedPane workRecordTabbedPane = new JTabbedPane(JTabbedPane.TOP);
+        workRecordTabbedPane = new JTabbedPane(JTabbedPane.TOP);
         workRecordTabbedPane.setFont(new Font("微软雅黑", Font.PLAIN, 14));
 
         // OP80 工位:当前工位 + 所有工位
@@ -762,6 +787,7 @@ public class MesClient extends JFrame {
 
         // 当前工位Tab(使用配置文件中的 mes.gw)
         workRecordPanels[0] = new WorkRecordPanel(mes_gw, mes_line_sn);
+        workRecordPanelCurrent = workRecordPanels[0];
         workRecordTabbedPane.addTab(mes_gw, null, workRecordPanels[0], "查询" + mes_gw + "的工作记录");
 
         // 所有工位Tab(查询整条产线所有工位)
@@ -816,6 +842,187 @@ public class MesClient extends JFrame {
         MesClient.status_menu.setText(msg);
     }
 
+    /** 工位变化后刷新顶部工位标签和窗口标题。 */
+    private static void refreshStationUi() {
+        String gwText = mes_gw + (mes_gw_des == null || mes_gw_des.trim().isEmpty() ? "" : " - " + mes_gw_des);
+        if (gwLabel != null) {
+            gwLabel.setText("工位:" + gwText);
+        }
+        String title = "MES系统客户端:" + gwText;
+        if (mesClientFrame != null) {
+            mesClientFrame.setTitle(title);
+        }
+        if (welcomeWin != null) {
+            welcomeWin.setTitle(title);
+        }
+    }
+
+    /** 按当前工位/当前登录用户刷新开班点检页面,不重启也能看到新工位的数据。 */
+    public static void reloadCheckPage() {
+        if (jfxPanel2 == null) {
+            return;
+        }
+        String ucode = user_menu == null ? "" : user_menu.getText();
+        String url = "http://" + mes_server_ip + ":8980/js/a/mes/mesProcessCheckRecord/ulist"
+                + "?ucode=" + ucode + "&oprno=" + mes_gw + "&lineSn=" + mes_line_sn
+                + (sessionid == null || sessionid.trim().isEmpty() ? "" : "&__sid=" + sessionid);
+        jfxPanel2.loadUrl(url);
+        log.info("开班点检页面已按工位刷新: {}", url);
+    }
+
+    /**
+     * 更改工位。工位号同时用于:扫码校验/结果上传等 HTTP 接口、开班点检页面、工作记录查询。
+     * 先写回 config/config.properties,成功后才切换内存和界面,避免界面与实际请求工位不一致。
+     */
+    public static boolean changeStation(String newGw) {
+        if (newGw == null || newGw.trim().isEmpty()) {
+            return false;
+        }
+        final String gw = newGw.trim().toUpperCase(java.util.Locale.ROOT);
+        if (!ConfigUtil.saveProperty("mes.gw", gw)) {
+            log.error("更改工位失败:写入 config/config.properties 失败, gw={}", gw);
+            return false;
+        }
+
+        mes_gw = gw;
+        String des = OprnoUtil.getGwDes(mes_line_sn, gw);
+        mes_gw_des = des == null ? "" : des;
+
+        refreshStationUi();
+        reloadCheckPage();
+
+        // 当前工位的工作记录查询条件同步
+        if (workRecordPanelCurrent != null) {
+            workRecordPanelCurrent.changeOprno(gw);
+        }
+        if (workRecordTabbedPane != null && workRecordTabbedPane.getTabCount() > 0) {
+            workRecordTabbedPane.setTitleAt(0, gw);
+            workRecordTabbedPane.setToolTipTextAt(0, "查询" + gw + "的工作记录");
+        }
+
+        // 清空当前加工状态,物料绑定按新工位重新拉取
+        resetScanA();
+        setMenuStatus("工位已切换为 " + gw + (mes_gw_des.isEmpty() ? "" : "(" + mes_gw_des + ")"), 0);
+        log.info("工位已更改: gw={}, des={}, config={}", gw, mes_gw_des, ConfigUtil.findConfigFile());
+        return true;
+    }
+
+    /** 设置菜单里的「更改工位」入口。 */
+    public static void showChangeStationDialog() {
+        if (work_status != null && work_status != 0) {
+            JOptionPane.showMessageDialog(mesClientFrame,
+                    "当前有工件正在加工/等待结果,不能更改工位。\n"
+                            + "请先完成当前工件,或点「设置-刷新工件」复位后再试。",
+                    "更改工位", JOptionPane.WARNING_MESSAGE);
+            return;
+        }
+
+        String oldGw = mes_gw == null ? "" : mes_gw.trim();
+        String line = mes_line_sn == null ? "" : mes_line_sn.trim();
+        String input = (String) JOptionPane.showInputDialog(mesClientFrame,
+                "当前工位:" + oldGw + "\n产线编号:" + line
+                        + "\n\n请输入新的工位号(最多 8 位字母/数字,例如 OP040、INSP030A):",
+                "更改工位", JOptionPane.QUESTION_MESSAGE, null, null, oldGw);
+        if (input == null) {
+            return;
+        }
+        String gw = input.trim().toUpperCase(java.util.Locale.ROOT);
+        if (gw.isEmpty()) {
+            setMenuStatus("工位号不能为空", -1);
+            return;
+        }
+        if (!gw.matches("[A-Z0-9_-]{1,8}")) {
+            JOptionPane.showMessageDialog(mesClientFrame,
+                    "工位号格式不正确:只允许 1~8 位字母、数字、下划线或短横线。",
+                    "更改工位", JOptionPane.WARNING_MESSAGE);
+            return;
+        }
+        if (gw.equals(oldGw)) {
+            setMenuStatus("工位号未变化", 0);
+            return;
+        }
+
+        String des = OprnoUtil.getGwDes(line, gw);
+        if (des == null || des.isEmpty()) {
+            int unknown = JOptionPane.showConfirmDialog(mesClientFrame,
+                    "本地工位表未匹配到工位 " + gw + " 的名称。\n"
+                            + "请确认 MES 后台该产线已配置此工位,否则扫码/点检会失败。\n\n仍要设置为该工位吗?",
+                    "更改工位", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
+            if (unknown != JOptionPane.OK_OPTION) {
+                return;
+            }
+            des = "";
+        }
+
+        int confirm = JOptionPane.showConfirmDialog(mesClientFrame,
+                "确认更改工位?\n\n工位号:" + oldGw + "  →  " + gw
+                        + "\n工位名称:" + (des.isEmpty() ? "(未匹配)" : des)
+                        + "\n\n更改后会立即写入 config/config.properties,"
+                        + "并同步刷新开班点检、工作记录和物料绑定,无需重启客户端。",
+                "确认更改工位", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
+        if (confirm != JOptionPane.OK_OPTION) {
+            return;
+        }
+
+        if (changeStation(gw)) {
+            JOptionPane.showMessageDialog(mesClientFrame,
+                    "工位已更改:" + gw + (des.isEmpty() ? "" : "(" + des + ")")
+                            + "\n配置文件已更新,开班点检已按新工位刷新。",
+                    "更改工位", JOptionPane.INFORMATION_MESSAGE);
+        } else {
+            JOptionPane.showMessageDialog(mesClientFrame,
+                    "写入 config/config.properties 失败,工位未更改。\n"
+                            + "请检查程序目录下 config 目录是否可写。",
+                    "更改工位", JOptionPane.WARNING_MESSAGE);
+        }
+    }
+
+    /**
+     * 隐藏解锁:先双击「心跳」值,15 秒内再双击「登录用户」值,
+     * 设置菜单才显示「更改工位」。文字标签和值按钮都支持。
+     */
+    private static void bindStationGesture(JComponent comp, final boolean heartbeatStep) {
+        if (comp == null) {
+            return;
+        }
+        comp.addMouseListener(new MouseAdapter() {
+            private long lastClickAt = 0L;
+
+            @Override
+            public void mouseClicked(MouseEvent e) {
+                if (!SwingUtilities.isLeftMouseButton(e)) {
+                    return;
+                }
+                long now = System.currentTimeMillis();
+                // 兼容标准双击,也兼容两次稍慢的单击(现场“点两下”)
+                boolean clickedTwice = e.getClickCount() >= 2 || (now - lastClickAt <= 700L);
+                lastClickAt = now;
+                if (!clickedTwice) {
+                    return;
+                }
+                if (heartbeatStep) {
+                    stationGestureHeartClicked = true;
+                    stationGestureHeartAt = System.currentTimeMillis();
+                    log.info("工位菜单解锁: 心跳双击 1/2");
+                    return;
+                }
+                if (!stationGestureHeartClicked) {
+                    return;
+                }
+                stationGestureHeartClicked = false;
+                if (System.currentTimeMillis() - stationGestureHeartAt > STATION_GESTURE_TIMEOUT_MS) {
+                    log.info("工位菜单解锁: 超时,请重新双击「心跳」");
+                    return;
+                }
+                if (changeStationMenu != null) {
+                    changeStationMenu.setVisible(true);
+                    log.info("工位菜单已解锁");
+                    setMenuStatus("已解锁「设置-更改工位」", 0);
+                }
+            }
+        });
+    }
+
     public static void getMaterailData(){
         try{
             JSONObject retObj = DataUtil.getBindMaterail();

+ 11 - 0
src/com/mes/ui/WorkRecordPanel.java

@@ -63,6 +63,17 @@ public class WorkRecordPanel extends JPanel {
         initUI();
     }
 
+    /** 更改工位后同步当前工位查询条件并刷新数据。 */
+    public void changeOprno(String newOprno) {
+        this.oprno = newOprno;
+        this.isAllStation = (newOprno == null || newOprno.isEmpty());
+        if (statusLabel != null) {
+            statusLabel.setText("工位:" + (isAllStation ? "所有工位" : newOprno));
+        }
+        this.pageNo = 1;
+        refreshData();
+    }
+
     /**
      * 初始化UI
      */

+ 122 - 0
src/com/mes/util/ConfigUtil.java

@@ -0,0 +1,122 @@
+package com.mes.util;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.List;
+import java.util.Properties;
+import java.util.regex.Pattern;
+
+/**
+ * 配置读取工具:外部 config/config.properties 优先,其次 jar 内置。
+ * 外部文件查找顺序:<程序目录>/config/config.properties、<当前目录>/config/config.properties。
+ * 现场换工控机/换工位时改外部文件即可,不用重新打包。
+ */
+public class ConfigUtil {
+
+    private static final String CONFIG_RELATIVE_PATH = "config" + File.separator + "config.properties";
+
+    /** 程序所在目录:打 jar 时是 jar 的父目录,IDE 里是 classes 输出目录。 */
+    public static File getAppDir() {
+        try {
+            File loc = new File(ConfigUtil.class.getProtectionDomain().getCodeSource().getLocation().toURI());
+            return loc.isFile() ? loc.getParentFile() : loc;
+        } catch (Throwable t) {
+            return new File(System.getProperty("user.dir", "."));
+        }
+    }
+
+    /** 查找已存在的外部配置,找不到返回 null。 */
+    public static File findConfigFile() {
+        File[] candidates = {
+                new File(getAppDir(), CONFIG_RELATIVE_PATH),
+                new File(System.getProperty("user.dir", "."), CONFIG_RELATIVE_PATH)
+        };
+        for (File f : candidates) {
+            if (f.isFile()) {
+                return f;
+            }
+        }
+        return null;
+    }
+
+    /** 写入时使用的配置文件:已有外部文件用它,否则在程序目录新建。 */
+    private static File configFileForWrite() {
+        File existing = findConfigFile();
+        if (existing != null) {
+            return existing;
+        }
+        return new File(getAppDir(), CONFIG_RELATIVE_PATH);
+    }
+
+    public static InputStream openConfigStream() throws IOException {
+        File f = findConfigFile();
+        if (f != null) {
+            return new FileInputStream(f);
+        }
+        InputStream is = ClassLoader.getSystemResourceAsStream("config/config.properties");
+        if (is == null) {
+            throw new FileNotFoundException("找不到配置文件 config/config.properties(外部和内置都不存在)");
+        }
+        return is;
+    }
+
+    public static Properties loadProperties() throws IOException {
+        Properties pro = new Properties();
+        try (InputStream is = openConfigStream();
+             BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
+            pro.load(br);
+        }
+        return pro;
+    }
+
+    /**
+     * 修改/新增配置文件中的配置项。
+     * 没有外部文件时先从内置配置复制一份,保证其余配置不丢。
+     */
+    public static boolean saveProperty(String key, String value) {
+        File target = configFileForWrite();
+        try {
+            if (!target.isFile()) {
+                File parent = target.getParentFile();
+                if (parent != null && !parent.exists() && !parent.mkdirs()) {
+                    throw new IOException("无法创建配置目录: " + parent);
+                }
+                InputStream builtIn = ClassLoader.getSystemResourceAsStream("config/config.properties");
+                if (builtIn != null) {
+                    try (InputStream in = builtIn) {
+                        Files.copy(in, target.toPath());
+                    }
+                } else {
+                    Files.write(target.toPath(),
+                            (key + "=" + value + System.lineSeparator()).getBytes(StandardCharsets.UTF_8));
+                }
+            }
+
+            List<String> lines = Files.readAllLines(target.toPath(), StandardCharsets.UTF_8);
+            Pattern p = Pattern.compile("^\\s*" + Pattern.quote(key) + "\\s*=.*$");
+            boolean replaced = false;
+            for (int i = 0; i < lines.size(); i++) {
+                String line = lines.get(i);
+                if (!line.trim().startsWith("#") && p.matcher(line).matches()) {
+                    lines.set(i, key + "=" + value);
+                    replaced = true;
+                    break;
+                }
+            }
+            if (!replaced) {
+                lines.add(key + "=" + value);
+            }
+            Files.write(target.toPath(), lines, StandardCharsets.UTF_8);
+            return true;
+        } catch (Exception e) {
+            return false;
+        }
+    }
+}