Java开发需求:解析URL末尾数字并匹配Excel对应分类
完整Java实现方案:URL解析 + Excel设备ID校验与分类查询
我来帮你搞定这个需求,下面是分模块的实现代码,包含URL解析、Excel数据读取、以及校验查询的完整逻辑,直接就能用:
1. 先搞定URL末尾数字解析
这里提供两种可靠的方式,你可以选一种适合你的场景:
方式一:路径拆分法(适合URL格式固定的场景)
import java.net.MalformedURLException; import java.net.URL; public class UrlParser { public static Long extractDeviceIdFromUrl(String urlStr) throws MalformedURLException { URL url = new URL(urlStr); String path = url.getPath(); // 拆分路径片段,取最后一段作为设备ID String[] pathSegments = path.split("/"); String lastSegment = pathSegments[pathSegments.length - 1]; try { return Long.parseLong(lastSegment); } catch (NumberFormatException e) { throw new IllegalArgumentException("URL末尾不是有效的数字设备ID", e); } } }
方式二:正则匹配法(适合URL格式可能有变化的场景)
import java.util.regex.Matcher; import java.util.regex.Pattern; public class UrlParser { // 匹配URL末尾的数字片段 private static final Pattern DEVICE_ID_PATTERN = Pattern.compile("/(\\d+)$"); public static Long extractDeviceIdFromUrl(String urlStr) { Matcher matcher = DEVICE_ID_PATTERN.matcher(urlStr); if (!matcher.find()) { throw new IllegalArgumentException("URL中未找到有效的设备ID"); } try { return Long.parseLong(matcher.group(1)); } catch (NumberFormatException e) { throw new IllegalArgumentException("提取到的内容不是有效数字设备ID", e); } } }
2. Excel数据读取与校验查询
这里用Apache POI库处理Excel(支持.xls和.xlsx格式),先给项目添加依赖:
Maven依赖(如果用Maven管理项目)
<dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.5</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.5</version> </dependency> </dependencies>
核心Excel处理代码
import org.apache.poi.ss.usermodel.*; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class ExcelDeviceChecker { // 内存缓存:设备ID -> 所属City/County分类 private final Map<Long, String> deviceCategoryMap = new HashMap<>(); // 初始化时加载Excel数据到缓存 public ExcelDeviceChecker(String excelFilePath) throws IOException { try (Workbook workbook = WorkbookFactory.create(new FileInputStream(excelFilePath))) { Sheet sheet = workbook.getSheetAt(0); // 默认取第一个工作表 Row headerRow = sheet.getRow(0); // 表头行 // 先定位各关键列的索引 int deviceIdColIndex = -1; int cityColIndex = -1; int countyColIndex = -1; for (Cell cell : headerRow) { String cellValue = cell.getStringCellValue().trim(); switch (cellValue) { case "Device ID": deviceIdColIndex = cell.getColumnIndex(); break; case "City": cityColIndex = cell.getColumnIndex(); break; case "County": countyColIndex = cell.getColumnIndex(); break; } } // 校验必要列是否存在 if (deviceIdColIndex == -1 || (cityColIndex == -1 && countyColIndex == -1)) { throw new IllegalArgumentException("Excel缺少必要列:Device ID 或 City/County"); } // 读取数据行(跳过表头) for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row == null) continue; // 获取设备ID Cell deviceIdCell = row.getCell(deviceIdColIndex); if (deviceIdCell == null) continue; Long deviceId; if (deviceIdCell.getCellType() == CellType.NUMERIC) { deviceId = (long) deviceIdCell.getNumericCellValue(); } else if (deviceIdCell.getCellType() == CellType.STRING) { try { deviceId = Long.parseLong(deviceIdCell.getStringCellValue().trim()); } catch (NumberFormatException e) { continue; // 跳过无效设备ID的行 } } else { continue; } // 优先取City,无则取County String category = null; if (cityColIndex != -1) { Cell cityCell = row.getCell(cityColIndex); if (cityCell != null && cityCell.getCellType() == CellType.STRING) { category = cityCell.getStringCellValue().trim(); } } if (category == null && countyColIndex != -1) { Cell countyCell = row.getCell(countyColIndex); if (countyCell != null && countyCell.getCellType() == CellType.STRING) { category = countyCell.getStringCellValue().trim(); } } if (category != null) { deviceCategoryMap.put(deviceId, category); } } } } // 查询设备分类,不存在则抛出异常 public String getDeviceCategory(Long deviceId) { String category = deviceCategoryMap.get(deviceId); if (category == null) { throw new IllegalArgumentException("设备ID " + deviceId + " 不存在于指定Excel中"); } return category; } }
3. 整合测试代码
把两部分逻辑整合起来,写个测试主方法:
public class Main { public static void main(String[] args) { try { // 1. 解析URL获取设备ID String url = "http://foxsd5174:3887/PD/outage/area/v1/device/40122480"; Long deviceId = UrlParser.extractDeviceIdFromUrl(url); System.out.println("解析到的设备ID:" + deviceId); // 2. 加载Excel并查询分类 ExcelDeviceChecker checker = new ExcelDeviceChecker("你的Excel文件路径.xlsx"); String category = checker.getDeviceCategory(deviceId); System.out.println("设备所属分类:" + category); } catch (Exception e) { e.printStackTrace(); // 可根据业务需求替换为自定义异常处理逻辑 } } }
注意事项
- 确保Excel文件路径正确,且程序有文件读取权限
- 如果Excel中Device ID是带前导零的字符串格式,需调整代码中的类型转换逻辑
- 可根据业务需求替换异常类型,比如自定义业务异常替代
IllegalArgumentException
内容的提问来源于stack exchange,提问作者Dipankar Ghosh
相关产品推荐
相关产品推荐

