是否有基于行号删除行的Java库?
我的目标是根据行号删除行。
实施例
删除行3,4,5输出应
我已经制定了一种工作方法
import org.apache.commons.io.FileUtils;
//...
private String removeLines(List<Integer> removeLines, File text) throws IOException {
List<String> textLines = FileUtils.readLines(text, StandardCharsets.UTF_8);
if (argsStrings.contains(Flags.DEBUG_FLAG)) {
String format = String.format("%d from %d need to be removed", removeLines.size(), textLines.size());
Logger.getLogger(App.class.getName()).log(Level.INFO, format);
}
int i = textLines.size();
while (!removeLines.isEmpty()) {
Integer line = new Integer(i + 1);
if (argsStrings.contains(Flags.DEBUG_FLAG)) {
String format = String.format("%4d. line inspected", line);
Logger.getLogger(App.class.getName()).log(Level.INFO, format);
}
if (removeLines.contains(line)) {
if (argsStrings.contains(Flags.DEBUG_FLAG)) {
String format = String.format("%4d. line removed, line text is below%n%s", line, textLines.get(i));
Logger.getLogger(App.class.getName()).log(Level.INFO, format);
}
textLines.remove(i);
removeLines.remove(line);
}
i--;
}
StringBuilder sb = new StringBuilder();
for (String line : textLines) {
sb.append(line);
sb.append(System.lineSeparator());
}
return sb.toString();
}
有更简单的方法吗?
答案 0 :(得分:1)
由于您似乎不介意将整个文件读入内存,请尝试以下操作:
private String removeLines(List<Integer> removeLines, File text) throws IOException {
List<String> textLines = FileUtils.readLines(text, StandardCharsets.UTF_8);
for(Integer removeLine : removeLines) {
textLines.remove(removeLine - 1); // -1, depending on how you specify removeLines
}
StringBuilder builder = new StringBuilder();
for(String line : textLines) {
builder.append(line).append(System.lineSeparator());
}
return builder.toString();
}
或者,您也可以使用LineIterator
:
private String removeLines(List<Integer> removeLines, File text) throws IOException {
StringBuilder builder = new StringBuilder();
LineIterator it = FileUtils.lineIterator(text, StandardCharsets.UTF_8);
try {
for (int i = 1; it.hasNext(); i++) {
String line = it.nextLine();
if(!removeLines.contains(i)) {
builder.append(line).append(System.lineSeparator());
}
}
} finally {
LineIterator.closeQuietly(it);
}
return builder.toString();
}