Search code examples
javabufferedreader

Deleting rest of line after X ":"


I've got a text file that has many lines. All that I care about is grabbing the first two words separated by a ":" and delete everything else after that.

Let's imagine the text file's contents look like this. The amount of ":" is random, I only want the first two words.

Sweet:Candy:Bear:Heaven:Ball
Mac:Cheese:Sauce:Code
Kebab:Shop:Space

I want to keep the first two words seperated by a ":" and delete everything else after that.

So I want to end up with something like this:

Sweet Candy
Mac Cheese
Kebab Shop

Reply to @Zabuza

With the current code below, I get this output:
Sweet
Candy
Sweet, Mac
Candy, Cheese
Sweet, Mac, Kebab
Candy, Cheese, Shop

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();
    }
}

Solution

  • 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.