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.