删除Java中文本文件内容后所有不需要的行
我已经了解了如何使用正则表达式模式在读取文件时删除所有空行,但我想删除所有内容之后所有不必要的行。例如: 输入: asdiofhpaiodf (空行,不删除) asdfihap[sdifh asdpiofhaspdif asiodfhpai[sdfh (空行,删除) (空行,删除)删除Java中文本文件内容后所有不需要的行,java,regex,Java,Regex,我已经了解了如何使用正则表达式模式在读取文件时删除所有空行,但我想删除所有内容之后所有不必要的行。例如: 输入: asdiofhpaiodf (空行,不删除) asdfihap[sdifh asdpiofhaspdif asiodfhpai[sdfh (空行,删除) (空行,删除) 输出: asdiofhpaiodf (空行) asdfihap[sdifh asdpiofhaspdif asiodfhpai[sdfh 你可以用剪刀修剪绳子的末端 String trimmedContents =
输出: asdiofhpaiodf (空行) asdfihap[sdifh asdpiofhaspdif asiodfhpai[sdfh
你可以用剪刀修剪绳子的末端
String trimmedContents = origContents.replaceAll("\\s+$", "");
为了补充斯特里比雪夫的答案,您可能还想使用
System.lineSeparator()
,而不是\s
(在大多数情况下\s
更有用,但我不知道您的需要)
既然我正在发布一个答案(还不能发表评论),我还是出去吧。我觉得你在试图重新调整文件的大小。(我只是再次使用System.lineSeparator()
来演示如何使用它。)
String regex = "[^"+ System.lineSeparator() + "]" + System.lineSeparator() + "$"; //or use "\\S\\s*$";
Matcher whiteSpace = Pattern.compile(regex).matcher("");
int threshold = 4; //number of characters to look back at the end of file.
byte[] readBytes = new byte[threshold]; //for whatever reason we can't just read in a string :/
try ( RandomAccessFile file = new RandomAccessFile(input_file, "rw")){
//start at the end of file, look for non line separator character.
long cursor;
for(cursor = file.length() - threshold; cursor > 0 ; cursor=cursor-threshold){
file.seek(cursor);
file.readFully(readBytes);
if(whiteSpace.reset(new String(readBytes)).find()){
cursor = cursor + whiteSpace.start() + 1;
break;
}
}
file.setLength(cursor);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
不知道性能会是什么样子,但我没有读入整个文件,而是从结尾开始。换句话说(更清楚)就是:要删除所有尾随的空行吗?定义“不需要的行”。你能展示一下你到目前为止都做了些什么吗?@laune是的,这就是我的意思。我不知道我从哪里开始。我不太清楚我们如何表现?我们如何表现?你确定你这里需要正则表达式吗?
trim()
似乎很适合这里。如果你接受\s+$
作为答案,那么这是一个重复的问题,应该是。这取决于原始内容应该包含什么,它与OP在Q和评论中写的内容相矛盾。奇怪。。。