-1

I would like to ask how I can pull information from a txt document ( my txt document contains like

Baggins, Bilbo, < bilbobaggins@bagend.com >, Y

Baggins, Frodo, < frodobaggins@bagend.com >, N

I have tried some stuff. I would also like to know how to store each part in a variable so i can edit them in a string builder/ use.trim to get rid of white spaces.

This is what i tried:

import java.io.FileNotFoundException;     
import java.lang.SecurityException;       
import java.util.Formatter;               
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;  
import java.util.Scanner;



/**
 *
 * 
 */
public class pullingEmails {
  public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

     // open contacts.txt, output data to the file then close contacts.txt
     try (Formatter output = new Formatter("contacts.txt")) {
         while (input.hasNext()) { // loop until end-of-file indicator
            try {
               // output new record to file; assumes valid input
               output.format("%s %s %s %s", input.next(),  
              input.next(), input.next(), input.next());
            } 
            catch (NoSuchElementException elementException) {
           System.err.println("No email address: " );
           input.nextLine(); // discard input so user can try again
        } 




     }
  }
  catch (SecurityException | FileNotFoundException | 
     FormatterClosedException e) {
     e.printStackTrace();
     System.exit(1); // terminate the program
      } 
   } 
}

I am not the best at Java and this is a new concept. I basically need it to print out what is in the file

Gamgee, Samwise, donleaveimsamwise@theShire.com,Y

                // every email has < > around them I will remove once i know how to pull the information correctly)

Baggins,Drogo,drogobagginstheshire.com,N

Erling,,erling@theshire.com,Y

Fortinbrass, Took,,Y

example of if statement for exception (not 100 percent sure how to format this):

if No email address
system.err.println("No email address: Chester, Steve,, N");

if (!email.contains("@"))
system.err.println("Invalid email address: "<simon#gmail.com>". Missing @ symbol.");

if invalid character //(only capital, lowercase, and @ symbol aloud)
system.err.println ("Invalid character '%' at position 4 in last name: "Robe%tson")

My current output does not work. I tried to follow an example i had but that one was asking for information to put in the file at first. not sure how to read what is in a file already, print it out then be able to store each part in a variables like firstName, lastName, Email, Sub etc.

Muhammad Ali
  • 564
  • 3
  • 9
tmanrocks994
  • 129
  • 6

1 Answers1

1

See this question for how to read files in Java. As each line seems to consist of comma separated values, you can just use split to get the individual values as array. Using streams (or alternatively a for-each loop) you can clean those values, e.g. using strip to remove whitespaces and replaceAll to remove the brackets. For converting the array back into a line, you could use join. You can collect the lines using a String or better a StringBuilder.

Here is an example:

StringBuilder sb = new StringBuilder();
try {
    Files.lines(Path.of("test.txt")).forEach(x -> {
        String[] split = x.split(",");
        split = stream(split).map(y -> {
            String cleaned = y.strip().replaceAll(">$|^<", "").strip();
            return cleaned;
        }).toArray(String[]::new);
        String email = split[2];
        // TODO: other data
        if (email.isBlank()) {
            System.err.println("No email address");
        }
        // TODO: other checks
        sb.append(String.join(", ", split));
        sb.append(System.lineSeparator());
    });
} catch (IOException e) {
    e.printStackTrace();
}

String result = sb.toString();
user7217806
  • 1,714
  • 2
  • 7
  • 10