Java命令行参数传参实现txt读取与JSON写入的问题排查
问题根因
异常来自两个核心逻辑错误:
- 保存JSON时传参写错:遍历参数匹配到
.json后缀项时,你固定给SaveDocumentsToJSON传了args[0]。当按顺序传入TextFile.txt outputFile.json时,args[0]就是第一个参数即txt源文件路径,等于直接把JSON内容写进了txt文件,自然会出现txt被覆写、指定json文件不生成的现象。 - 逻辑顺序混乱:把参数解析和IO操作混在同一个遍历循环里,没有提前校验必填参数是否齐全,传入多个同后缀文件时会出现非预期执行;另外读文件的
BufferedReader没有做安全释放,存在资源泄漏风险。
修复方案
调整逻辑顺序:先遍历所有参数提取出txt输入路径、json输出路径,校验两个参数都合法后,再按顺序执行读、写操作,不要边遍历参数边执行IO。同时修复文件读取的资源释放问题。
修复后的核心代码如下:
public static void main(String[] args) { BTextLoader loader = new BTextLoader(); String txtInputPath = null; String jsonOutputPath = null; // 第一步:解析命令行参数,提取两个目标文件路径 for (String arg : args) { if (arg.endsWith(".txt")) { txtInputPath = arg; } if (arg.endsWith(".json")) { jsonOutputPath = arg; } } // 第二步:校验参数完整性,缺项直接报错退出 if (txtInputPath == null || jsonOutputPath == null) { System.err.println("参数错误:需同时传入.txt格式的输入文件路径、.json格式的输出文件路径,参数间用空格分隔"); return; } // 第三步:按顺序执行读写逻辑 loader.LoadTextFile(txtInputPath); loader.SaveDocumentsToJSON(jsonOutputPath); } // 修复文件读取的资源泄漏问题 public void LoadTextFile(String filePath) { System.out.println("Loading file..."); File inFile = new File(filePath); // 用try-with-resources自动释放流资源,无需手动close try (BufferedReader br = new BufferedReader(new FileReader(inFile))) { String line = br.readLine(); Integer counter = 0; while (line != null) { if (line.trim().length() > 0) { documents.put("doc" + counter, line); counter++; } line = br.readLine(); } } catch (Exception e) { System.out.println("File Load Failed"); // 打印异常栈方便定位问题,不要直接吞异常 e.printStackTrace(); } }
验证方式
修复后在Eclipse运行配置的Arguments页签中,传入空格分隔的两个参数TextFile.txt outputFile.json即可:
- 程序会自动识别txt参数作为读取源,json参数作为输出目标
- 不会再覆写原txt文件,JSON内容会正常写入指定的outputFile.json文件
内容的提问来源于stack exchange,提问作者Bluetail
相关产品推荐
相关产品推荐

