Java文件内容拷贝替换时丢失换行符问题求助
问题原因
- 核心原因1:
BufferedReader.readLine()方法读取每行内容时,会自动丢弃行尾的换行符(\n/\r\n),直接追加字符串自然不会保留换行格式。 - 核心原因2:现有循环逻辑存在错误:每行读取后连续追加3次修改后的行内容,会导致原文件每行被重复写入3次,并非在同一行完成所有关键词替换。
- 额外问题:代码中定义了
pathwriter变量但未使用,写入时用到的pathscxmlout没有声明定义,会导致编译报错。
修复方案
修改读取替换的循环逻辑,同一行完成所有关键词替换后,手动追加跨平台兼容的换行符即可,同时推荐使用try-with-resources语法自动关闭流资源,避免资源泄漏。
修正后的完整代码
public class FileDefinition { String result = ""; String pathxml = pathxmlin; String pathconf = pathfileconf; //func to be recalled in the main for the different files public String getPropValues() throws IOException { try { Properties prop = new Properties(); String pathconf = this.pathconf; String pathxml = this.pathxml; //Read file conf try (InputStream is = new FileInputStream(pathconf); BufferedReader br = new BufferedReader(new InputStreamReader(is))) { prop.load(br); } // get the property value and print it out String name = prop.getProperty("name"); String loc = prop.getProperty("location"); String id = prop.getProperty("PropID"); //research fields to be changed String searchname = "RotaionToInside"; String searchlocation = "location"; String searchpropid = "PropOfJobID"; String lineContent; StringBuilder contentBuilder = new StringBuilder(); //Read scxml file to get the format try (BufferedReader rb = new BufferedReader(new FileReader(pathxml))) { while ((lineContent = rb.readLine()) != null) { // 同一行完成所有关键词替换 String modifiedLine = lineContent.replaceAll(searchlocation, loc) .replaceAll(searchpropid, id) .replaceAll(searchname, name); // 追加修改后的行 + 跨平台兼容换行符 contentBuilder.append(modifiedLine).append(System.lineSeparator()); } } String pathwriter = pathxml + name + ".scxml"; // 写入新文件 try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File(pathwriter)))) { bw.write(contentBuilder.toString()); } } catch (Exception e) { System.out.println("Exception: " + e); } return result; } }
内容的提问来源于stack exchange,提问作者Webpe
相关产品推荐
相关产品推荐

