如何删除换行符Java
使用 replaceAll() 方法
通过正则表达式匹配换行符并替换为空字符串:

String text = "Hello\nWorld\r\n";
String result = text.replaceAll("\\r|\\n", "");
使用 StringUtils 工具类(Apache Commons)
若项目中已引入 Apache Commons Lang,可直接调用:

String text = "Hello\nWorld\r\n";
String result = StringUtils.replaceChars(text, "\r\n", "");
遍历字符手动拼接
通过遍历字符串,过滤掉换行符字符:
String text = "Hello\nWorld\r\n";
StringBuilder sb = new StringBuilder();
for (char c : text.toCharArray()) {
if (c != '\n' && c != '\r') {
sb.append(c);
}
}
String result = sb.toString();
处理多平台换行符差异
不同操作系统换行符可能为 \n(Unix)、\r\n(Windows)或 \r(旧版Mac),建议兼容处理:
String text = "Hello\nWorld\r\n";
String result = text.replace("\r", "").replace("\n", "");




