如何从 Java 中的文件中删除换行符? [英] How to remove line breaks from a file in Java?

查看:45
本文介绍了如何从 Java 中的文件中删除换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Java 中以适用于 Windows 和 Linux 的方式替换字符串中的所有换行符(即没有回车/换行/换行等操作系统特定问题)?

How can I replace all line breaks from a string in Java in such a way that will work on Windows and Linux (ie no OS specific problems of carriage return/line feed/new line etc.)?

我已经尝试过(注意 readFileAsString 是一个将文本文件读入字符串的函数):

I've tried (note readFileAsString is a function that reads a text file into a String):

String text = readFileAsString("textfile.txt");
text.replace("
", "");

但这似乎不起作用.

如何做到这一点?

推荐答案

需要将text设置为text.replace()的结果:

String text = readFileAsString("textfile.txt");
text = text.replace("
", "").replace("
", "");

这是必要的,因为字符串是不可变的——调用 replace 不会改变原来的字符串,它会返回一个被改变的新字符串.如果您不将结果分配给 text,则该新字符串将丢失并被垃圾收集.

This is necessary because Strings are immutable -- calling replace doesn't change the original String, it returns a new one that's been changed. If you don't assign the result to text, then that new String is lost and garbage collected.

至于获取任何环境的换行符字符串——可通过调用 System.getProperty("line.separator") 获得.

As for getting the newline String for any environment -- that is available by calling System.getProperty("line.separator").

这篇关于如何从 Java 中的文件中删除换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆