Ant replace 含有中文时的乱码问题

本文介绍在Ant构建工具中处理含有中文的文件时遇到的乱码问题,并提供了解决方案,即通过指定合适的字符集编码来避免乱码出现。

在Ant中对含有中文的文件作替换操作时会出现乱码的现像:

<replace file="${filename}" token="tokenstring" value="valuestring"/>

这主要是由于Ant操作文件时的字符集影响,可以在使用该操作时指定字符集的编码方式:

<replaceencoding="utf-8" dir="${basedir}">

     <include name="${filename}"/>

     <replacefilter token="tokenstring" value="valuestring" />

</replace>



<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="weaver.general.Util"%> <%@page import="weaver.conn.RecordSet"%> <%@page import="com.alibaba.fastjson.JSONObject"%> <%@page import="com.alibaba.fastjson.JSONArray"%> <%@page import="java.net.URLEncoder"%> <% request.setCharacterEncoding("UTF-8"); // 基础参数 String pddhRaw = Util.null2String(request.getParameter("PDDH")); String pddh = "0"; try { pddh = String.valueOf(Integer.parseInt(pddhRaw)); } catch(Exception e){ pddh = "0"; } // 查询参数(做简单清洗,避免注入/通配符滥用) String q_zcbm = Util.null2String(request.getParameter("q_zcbm")).replaceAll("[%'_]", ""); String q_syr = Util.null2String(request.getParameter("q_syr")).replaceAll("[%'_]", ""); String q_sybm = Util.null2String(request.getParameter("q_sybm")).replaceAll("[%'_]", ""); // 组装 SQL StringBuilder sql = new StringBuilder(); sql.append("select zcmc,zcbm,zcqc,zcgz,zclz,zcfl,ppxh,syr,sybm,rkrq,pdbz,zczt,pdsj,zcgs ") .append("from uf_CKBGQD where pddh=").append(pddh); if(q_zcbm.length()>0){ sql.append(" and zcbm like '%").append(q_zcbm).append("%'"); } if(q_syr.length()>0 ){ sql.append(" and syr like '%").append(q_syr ).append("%'"); } if(q_sybm.length()>0){ sql.append(" and sybm like '%").append(q_sybm).append("%'"); } // 查询 JSONArray jsonArray = new JSONArray(); RecordSet rs = new RecordSet(); rs.execute(sql.toString()); while(rs.next()){ JSONObject row = new JSONObject(); row.put("zcmc", rs.getString("zcmc")); row.put("zcbm", rs.getString("zcbm")); row.put("zcqc", rs.getString("zcqc")); row.put("zcgz", rs.getString("zcgz")); row.put("zclz", rs.getString("zclz")); row.put("zcfl", rs.getString("zcfl")); row.put("ppxh", rs.getString("ppxh")); row.put("syr", rs.getString("syr")); row.put("sybm", rs.getString("sybm")); // 使用部门 row.put("rkrq", rs.getString("rkrq")); row.put("pdbz", rs.getString("pdbz")); row.put("zczt", rs.getString("zczt")); row.put("pdsj", rs.getString("pdsj")); row.put("zcgs", rs.getString("zcgs")); // 资产归属 jsonArray.add(row); } // 把数据输出给前端 JS 使用(便于导出/前端处理) String dataJson = jsonArray.toJSONString(); %> <!DOCTYPE html> <html> <head> <title>查看报告</title> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"> <link rel="stylesheet" href="/cloudstore/resource/pc/com/v1/index.min.css?v=1715806801819"> <link rel="stylesheet" href="/cloudstore/resource/pc/com/v1/ecCom.min.css?v=1715806801819"> <script type="text/javascript" src="/js/My97DatePicker/WdatePicker.js" charset="gb2312"></script> <script type="text/javascript" src="/js/jquery/jquery-3.7.1.min.js"></script> <style> .toolbar { display:flex; gap:8px; align-items:center; padding:10px 0; flex-wrap:wrap; } .toolbar input { height:32px; padding:0 8px; } .toolbar .btn { height:32px; padding:0 12px; border:1px solid #d9d9d9; border-radius:4px; background:#fff; cursor:pointer; } .toolbar .btn.primary { background:#1677ff; color:#fff; border-color:#1677ff; } .action-link { color:#1677ff; cursor:pointer; } </style> </head> <body style="width:100%; height:100%;"> <div id="container"> <div class="coms-mode-docker coms-mode-search"> <div id="cube_search_9"> <div class="ant-spin-nested-loading"> <div class="ant-spin-container"> <div style="height: 100%;"> <div class="wea-new-top-content" style="height: 691.175px; overflow-y: hidden;"> <div class="cube-list-wrapper"> <!-- 查询工具条 & 导出 --> <form id="queryForm" method="get" class="toolbar"> <input type="hidden" name="PDDH" value="<%=pddh%>" /> <label>物料编码:</label> <input type="text" name="q_zcbm" value="<%=q_zcbm%>" placeholder="支持模糊查询"> <label>使用人:</label> <input type="text" name="q_syr" value="<%=q_syr%>" placeholder="支持模糊查询"> <label>使用部门:</label> <input type="text" name="q_sybm" value="<%=q_sybm%>" placeholder="支持模糊查询"> <button type="submit" class="btn primary">查询</button> <button type="button" class="btn" id="btnReset">重置</button> <button type="button" class="btn" id="btnExport">导出当前结果</button> </form> <div class="wea-new-table cube-list-table pageAutoWrap"> <div style="width: 100%; height: 100%;"> <div class="cube-list-table clearfix"> <div class="ant-spin-nested-loading"> <div class="ant-spin-container"> <div class="ant-table ant-table-large ant-table-fixed-header ant-table-scroll-position-left"> <div class="ant-table-content" style="padding-left: 0px; padding-right: 0px;"> <div class="ant-table-scroll"> <span> <div class="ant-table-header" style="overflow-x: scroll; margin-bottom: 0px !important; padding-bottom: 0px !important;"> <table class="ant-table-fixed" style="width: 100%;"> <colgroup> <col style="width: 14%"> <col style="width: 10%"> <col style="width: 14%"> <col style="width: 8%"> <col style="width: 8%"> <col style="width: 8%"> <col style="width: 10%"> <col style="width: 8%"> <col style="width: 10%"> <col style="width: 8%"> <col style="width: 8%"> <col style="width: 10%"> </colgroup> <thead class="ant-table-thead"> <tr style="height: 41.6px;"> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">物料编码</span></th> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">资产名称</span></th> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">资产全称</span></th> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">资产类属</span></th> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">资产归属</span></th> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">资产分类</span></th> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">品牌/型号</span></th> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">使用人</span></th> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">使用部门</span></th> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">入库日期</span></th> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">资产状态</span></th> <th class="react-resizable"><span class="ant-table-column-sorterN text-elli">操作</span></th> </tr> </thead> </table> </div> <div class="ant-table-body" style="overflow: auto scroll; max-height: 600px; min-height: auto;"> <table class="ant-table-fixed" style="width: 100%;" id="dataTable"> <colgroup> <col style="width: 14%"> <col style="width: 10%"> <col style="width: 14%"> <col style="width: 8%"> <col style="width: 8%"> <col style="width: 8%"> <col style="width: 10%"> <col style="width: 8%"> <col style="width: 10%"> <col style="width: 8%"> <col style="width: 8%"> <col style="width: 10%"> </colgroup> <tbody class="ant-table-tbody"> <% if(jsonArray.size()>0){ for(int i=0;i<jsonArray.size();i++){ %> <tr class="ant-table-row ant-table-row-level-0"> <td class="react-resizable"><span class="wea-url"><%=jsonArray.getJSONObject(i).getString("zcbm")%></span></td> <td class="react-resizable"><span class="wea-url"><%=jsonArray.getJSONObject(i).getString("zcmc")%></span></td> <td class="react-resizable"><span class="wea-url"><%=jsonArray.getJSONObject(i).getString("zcqc")%></span></td> <td class="react-resizable"><span class="wea-url"><%=jsonArray.getJSONObject(i).getString("zclz")%></span></td> <td class="react-resizable"><span class="wea-url"><%=jsonArray.getJSONObject(i).getString("zcgs")%></span></td> <td class="react-resizable"><span class="wea-url"><%=jsonArray.getJSONObject(i).getString("zcfl")%></span></td> <td class="react-resizable"><span class="wea-url"><%=jsonArray.getJSONObject(i).getString("ppxh")%></span></td> <td class="react-resizable"><span class="wea-url"><%=jsonArray.getJSONObject(i).getString("syr")%></span></td> <td class="react-resizable"><span class="wea-url"><%=jsonArray.getJSONObject(i).getString("sybm")%></span></td> <td class="react-resizable"><span class="wea-url"><%=jsonArray.getJSONObject(i).getString("rkrq")%></span></td> <td class="react-resizable"><span class="wea-url"><%=jsonArray.getJSONObject(i).getString("zczt")%></span></td> <td class="react-resizable"> <span class="action-link" onclick="onDelete(this)">删除</span> </td> </tr> <% } } %> </tbody> </table> </div> </span> </div> </div> </div> </div> </div> <!-- ant-spin-container --> </div> </div> </div> <!-- table wrap --> </div> </div> </div> </div> </div> <!-- spin --> </div> </div> </div> <script> // 前端可用数据(用于导出) const tableData = <%=dataJson%>; // 重置查询 $("#btnReset").on("click", function(){ const base = location.pathname + "?PDDH=<%=pddh%>"; location.href = base; }); // 一键导出(把当前结果导成 CSV) $("#btnExport").on("click", function(){ if(!tableData || tableData.length === 0){ alert("没有可导出的数据"); return; } const headers = ["物料编码","资产名称","资产全称","资产类属","资产归属","资产分类","品牌/型号","使用人","使用部门","入库日期","资产状态","盘点备注","盘点间"]; const keys = ["zcbm","zcmc","zcqc","zclz","zcgs","zcfl","ppxh","syr","sybm","rkrq","zczt","pdbz","pdsj"]; // CSV 内容,含 BOM 以防中文乱码(Excel 友好) let csv = "\uFEFF" + headers.join(",") + "\n"; tableData.forEach(r=>{ const row = keys.map(k=>{ let val = (r[k] ?? "").toString().replace(/"/g,'""'); // 若包含逗号/引号/换行,按 CSV 规范用引号包裹 if(/[",\n]/.test(val)){ val = `"${val}"`; } return val; }).join(","); csv += row + "\n"; }); const blob = new Blob([csv], {type: "text/csv;charset=utf-8;"}); const url = URL.createObjectURL(blob); const a = document.createElement("a"); const ts = new Date(); const pad = n=> String(n).padStart(2,"0"); const name = `盘点清单_${ts.getFullYear()}${pad(ts.getMonth()+1)}${pad(ts.getDate())}_${pad(ts.getHours())}${pad(ts.getMinutes())}${pad(ts.getSeconds())}.csv`; a.href = url; a.download = name; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); }); // 删除:把该行的“物料编码”传给后端 function onDelete(el){ const $tr = $(el).closest("tr"); const zcbm = $tr.find("td").eq(0).text().trim(); // 第1列就是物料编码 if(!zcbm){ alert("未找到物料编码"); return; } if(!confirm("确认删除物料编码为【"+zcbm+"】的记录吗?")) return; // // TODO: 把 URL 换成你后端实际的删除接口 // $.ajax({ // url: "/api/ckbgqd/delete", // 例如:新建一个 Servlet/JSP 接口去处理删除 // type: "POST", // data: { zcbm: zcbm, pddh: "<%=pddh%>" }, // success: function(res){ // // 这里按你的后端返回格式调整 // // 假设返回 {success:true,msg:"ok"} // try{ // const r = typeof res === "string" ? JSON.parse(res) : res; // if(r.success){ // $tr.remove(); // }else{ // alert(r.msg || "删除失败"); // } // }catch(e){ // // 如果不是 JSON,就当成功处理 // $tr.remove(); // } // }, // error: function(){ // alert("请求失败,请稍后重试"); // } // }); var pddh = "<%=pddh%>"; <% String sql = "delete from uf_CKBGQD where pddh ='"<%=pddh%>"' and zcbm ="+"'"+zcbm+"'"; RecordSet rs1 = new RecordSet(); rs1.execute(rs1); %> } </script> </body> </html> 这个有错误,帮修复一下
最新发布
10-24
public void download(FileRequest fileRequest, HttpServletResponse response) throws IOException { String bucketKey = fileRequest.getBucketKey(); List<String> sourcePaths = fileRequest.getSourcePaths(); String p13 = fileRequest.getP13(); if (StrUtil.isEmpty(bucketKey) || CollectionUtil.isEmpty(sourcePaths) || StrUtil.isEmpty(p13)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write("非法请求参数"); return; } // 判断是否有桶 if (!fileBucketService.selectByBucketKey(bucketKey)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write("不存在该文件桶,请正确选择桶的key"); return; } try { List<Path> sources = new ArrayList<>(); for (String sourcePath : sourcePaths) { String processedSourcePath = normalizePath(sourcePath); Path source = Paths.get(originPath, bucketKey, p13, processedSourcePath); if (Files.exists(source)) { sources.add(source); } } if (sources.isEmpty()) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().write("没有找到有效的文件或文件夹"); return; } // 使用第一个选中项的名称作为zip文件名 String firstName = sources.get(0).getFileName().toString(); String zipFileName = firstName + ".zip"; // 设置响应头 response.setContentType("application/zip"); String finalFileName = URLEncoder.encode(zipFileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20"); response.addHeader("Content-Disposition", "attachment;filename*=utf-8''" + finalFileName); try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) { for (Path source : sources) { if (Files.isDirectory(source)) { addDirectoryToZip(zos, source, source.getFileName().toString()); } else { addFileToZip(zos, source, source.getFileName().toString()); } } zos.finish(); } } catch (Exception e) { logger.error("下载操作异常", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write("下载异常: " + e.getMessage()); } } /** * 将目录添加到zip文件中 * * @param zos ZipOutputStream对象 * @param source 源目录路径 * @param basePath 基础路径 * @throws IOException IO异常 */ private void addDirectoryToZip(ZipOutputStream zos, Path source, String basePath) throws IOException { Files.walkFileTree(source, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String entryName = basePath + "/" + source.relativize(file).toString().replace("\\", "/"); addFileToZip(zos, file, entryName); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { String entryName = basePath + "/" + source.relativize(dir).toString().replace("\\", "/") + "/"; zos.putNextEntry(new ZipEntry(entryName)); zos.closeEntry(); return FileVisitResult.CONTINUE; } }); } /** * 将文件添加到zip文件中 * * @param zos ZipOutputStream对象 * @param source 源文件路径 * @param entryName zip条目名称 * @throws IOException IO异常 */ private void addFileToZip(ZipOutputStream zos, Path source, String entryName) throws IOException { ZipEntry zipEntry = new ZipEntry(entryName); zos.putNextEntry(zipEntry); try (FileInputStream fis = new FileInputStream(source.toFile())) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { zos.write(buffer, 0, bytesRead); } } zos.closeEntry(); }为什么 zip文件的名称中文不会乱码,但是点开zip查看里面的文件,中文名称都乱码
08-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值