删除 X“:”之后的其余行

Deleting rest of line after X ":"

我有一个包含很多行的文本文件。我只关心用“:”分隔的前两个词,然后删除其他所有词。

让我们想象文本文件的内容如下所示。 “:”的数量是随机的,我只想要前两个字。

甜:糖:熊:天:球
Mac:Cheese:Sauce:Code
Kebab:Shop:Space

我想保留前两个单词,用“:”分隔,然后删除其他所有单词。

所以我想以这样的方式结束:

甜蜜的糖果
Mac奶酪
烤肉店

回复@Zabuza

使用下面的当前代码,我得到了这个输出:
甜蜜
糖果
亲爱的,Mac
糖果、奶酪
甜蜜,Mac,烤肉串
糖果、奶酪、商店

public void formatAccounts() throws InterruptedException {
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        String line;

        while ((line = br.readLine()) != null) {

            String[] parts = line.split(":");
            a.add(parts[0]);
            b.add(parts[1]);

            System.out.println(a);
            System.out.println(b);

            sleep(1000);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public void formatTxtFile() throws InterruptedException {
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        String line;
        while ((line = br.readLine()) != null) {
            String[] parts = line.split(":");
            System.out.println(parts[0] + " " +parts[1]);
            Thread.sleep(1000);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Create a file any where, and try to run the above code.you will get the expected result.

使用 Java 8 条流,您可以将其简化为如下所示:

Path pathToFile = Paths.get("test.txt");
Files.lines(pathToFile).map(l -> l.split(":")).forEach(a -> System.out.println(a[0] + " " + a[1]));

首先你引用输入文件:

Path pathToFile = Paths.get("nameOfFile.txt");

使用 Files.lines() 从文件中获取所有行,然后使用 map() 将每一行拆分为一个字符串数组,最后将前两个元素打印到控制台.