简体   繁体   English

从Java中的文件中删除多行中的一行

[英]Remove a single line among multiple lines from a file in Java

I have to remove all the single lines from a file that contains multiple lines.我必须从包含多行的文件中删除所有单行。 For example, suppose I have the input file like below,例如,假设我有如下输入文件,

file1.txt文件1.txt

ALTER TABLE <tablename>
MODIFY <some parameter>
    
ALTER TABLE <tablename> #this is a single line, so need to remove this

ALTER TABLE <tablename> #this is a single line, so need to remove this

ALTER TABLE <tablename>
MODIFY <some parameter>

ALTER TABLE <tablename> #this is a single line, so need to remove this

The output file should contain only the below lines,输出文件应仅包含以下行,

file2.txt文件2.txt

ALTER TABLE <tablename>
MODIFY <some parameter>

ALTER TABLE <tablename>
MODIFY <some parameter>

Any help would be appreciated.任何帮助,将不胜感激。

here some ideas might help you.这里的一些想法可能会对您有所帮助。

  1. when it's not first or last.make sure the line that before and after itself is empty then pass it当它不是第一个或最后一个时。确保之前和之后的行是空的然后通过它

  2. when it's first or last.当它是第一个或最后一个。 make sure when first after this is empty and the logic of last is the same.确保当 first after this 为空并且 last 的逻辑是相同的。

FileReader fileReader = new FileReader("/data/xx.text");
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = bufferedReader.lines().collect(Collectors.toList());
List<String> finalLines = new ArrayList<>();
if(lines.size() == 1){
    // it's empty
    return;
}
if(lines.size() == 2 && (lines.get(0)== null ||lines.get(1) == null)){
    return;
}
for (int i = 1; i < lines.size() - 1; i++) {
    if(i == 1 && lines.get(i + 1) == null){
        continue;
    }
    if(lines.get(i-1) == null && lines.get(i + 1) == null && lines.get(i) != null){
        continue;
    }

    finalLines.add(lines.get(i));
}
if(lines.get(lines.size() - 2) != null){
    finalLines.add(lines.get(lines.size() -1));
}
for (String finalLine : finalLines) {
    System.out.println(finalLine);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM