Java读取文件调用substring取值为空,如何读取55401开头的行
问题排查与修正方案
核心问题原因
- substring参数顺序错误:Java中
String.substring(int beginIndex, int endIndex)要求起始索引小于等于结束索引,beginIndex为包含的起始位置,endIndex为不包含的结束位置。你代码中shipDate6 = outPut.substring(105, 101);的起始索引105大于结束索引101,会直接抛出StringIndexOutOfBoundsException。你对整个循环做了异常捕获但catch块没有任何处理逻辑,异常抛出后当前循环内后续的所有赋值代码都会终止执行,导致qty6、shipDate7、qty7都停留在初始空值状态。 - 多行55401内容处理逻辑错误:你的文件中存在两行以55401开头的内容,现有代码中固定的shipDate、qty变量会被第二行55401的内容覆盖,且没有区分处理第一行的第6组数据和第二行的第7组数据,直接取第二行前6位赋值给shipDate7的逻辑不符合需求。
- 空异常捕获掩盖问题:空的catch块会吞掉所有运行时异常,你无法感知到索引越界这类错误的发生,非常不利于问题定位,开发调试阶段禁止使用空catch逻辑。
修正代码示例
public static void main(String[] args) throws IOException { File file = new File("C:\\Users\\Mail\\Desktop\\VDA Reader\\VDA.txt"); Scanner scan = new Scanner(file); String callOffs = "55401"; // 用集合存储结果,避免定义大量重复变量 List<String> shipDateList = new ArrayList<>(); List<String> qtyList = new ArrayList<>(); try { while (scan.hasNextLine()) { String outPut = scan.nextLine(); if(outPut.startsWith(callOffs)){ // 每组数据提取前先判断行长度是否足够,避免索引越界 if(outPut.length() >= 24) { shipDateList.add(outPut.substring(5, 11)); qtyList.add(outPut.substring(15, 24)); } if(outPut.length() >= 44) { shipDateList.add(outPut.substring(25, 31)); qtyList.add(outPut.substring(35, 44)); } if(outPut.length() >= 64) { shipDateList.add(outPut.substring(45, 51)); qtyList.add(outPut.substring(55, 64)); } if(outPut.length() >= 84) { shipDateList.add(outPut.substring(65, 71)); qtyList.add(outPut.substring(75, 84)); } if(outPut.length() >= 104) { shipDateList.add(outPut.substring(85, 91)); qtyList.add(outPut.substring(95, 104)); } // 修正shipDate6的索引顺序,可根据实际数据位置调整参数 if(outPut.length() >= 124) { shipDateList.add(outPut.substring(101, 107)); qtyList.add(outPut.substring(115, 124)); } } } } catch (Exception e){ // 打印异常信息方便定位问题 e.printStackTrace(); } scan.close(); // 批量输出结果 for (int i = 0; i < shipDateList.size(); i++) { System.out.println("Ship "+shipDateList.get(i) + " | QTY " + qtyList.get(i)); } }
额外提示
你需要先确认第一行55401内容中第6组日期的实际起止位置,调整对应substring的参数到正确值即可正常提取。如果需要提取第二行55401的其他组数据,按照同样的逻辑补充判断和提取代码即可。
内容的提问来源于stack exchange,提问作者Niklas
相关产品推荐
相关产品推荐

