Java代码换行大括号转行尾大括号:文件读取格式适配求助
解决Java文件读取丢失换行符和制表符导致格式转换失败的问题
首先,你的问题根源在于Scanner的nextLine()方法会丢弃每行末尾的换行符,而且你在拼接字符串时没有把这些换行符补回去——虽然行内的制表符\t会被nextLine()保留,但整个文件内容被拼接成了没有换行的长字符串,导致原有转换逻辑无法定位大括号的正确位置。
下面给你几个可行的解决方案:
方案1:修改Scanner读取逻辑,补回换行符
只需要在每次读取一行后手动添加换行符\n,就能完整保留文件中的换行和制表符,同时建议用StringBuilder代替直接字符串拼接,避免频繁创建字符串对象:
File sourceFile = new File("oldFormattedSourceCode.txt"); StringBuilder oldFormatString = new StringBuilder(); try (Scanner input = new Scanner(sourceFile)) { while (input.hasNextLine()) { oldFormatString.append(input.nextLine()).append("\n"); } System.out.println("Old Format String is: " + oldFormatString.toString()); } catch (FileNotFoundException ex) { System.out.print(ex.getMessage()); }
方案2:使用Java 11+的Files.readString()(最简洁)
Java 11及以上版本提供了Files.readString()方法,可以直接读取整个文件的内容,自动保留所有的换行符、制表符等空白字符,代码异常简洁:
File sourceFile = new File("oldFormattedSourceCode.txt"); String oldFormatString; try { oldFormatString = Files.readString(sourceFile.toPath()); System.out.println("Old Format String is: " + oldFormatString); } catch (IOException ex) { ex.printStackTrace(); }
方案3:使用BufferedReader读取(传统稳定方案)
如果你的项目还在使用Java 11以下的版本,BufferedReader是更高效的文件读取方式,同样可以补回换行符:
File sourceFile = new File("oldFormattedSourceCode.txt"); StringBuilder oldFormatString = new StringBuilder(); try (BufferedReader br = new BufferedReader(new FileReader(sourceFile))) { String line; while ((line = br.readLine()) != null) { oldFormatString.append(line).append("\n"); } } catch (IOException ex) { ex.printStackTrace(); }
额外提示:优化你的转换逻辑
你的现有转换代码可能存在一些边界问题,比如一行中有多个{、注释中的{会被误处理。如果需要更健壮的转换,可以用正则表达式精准匹配:
// 匹配换行前的空白+{,替换为行尾的 { String result = oldFormatString.replaceAll("\\s*\\{\n", " {\n"); // 处理制表符后的{ result = result.replaceAll("\\t\\{", "{");
这个方式比循环处理更稳定,能避免字符串索引错位的问题。
内容的提问来源于stack exchange,提问作者user7310905
相关产品推荐
相关产品推荐

