Reputation: 23
I've got a text file with a name (first+family name) on every line, from these names I want to create email addresses (in this format : [email protected].).
My plan is to do something like this:
The main thing I dont know how to do is splitting the names and putting them into correct arrays, I can split them but then they lose their grouping.
public static void main(String[] args) throws IOException
{
File file = new File("D:\\NetbeansProjects\\Emails\\src\\emails\\lijst.txt");
BufferedReader abc = new BufferedReader(new FileReader(file));
List<String> data = new ArrayList<String>();
String s;
while((s=abc.readLine())!=null) {
data.add(s);
}
abc.close();
System.out.println(data);
List<String> splitdata = new ArrayList<String>();
for(String strLine : data) {
String[] strWord = strLine.split("[\\s']");
for (String c : strWord) {
splitdata.add(c);
}
}
System.out.println(splitdata);
}
Upvotes: 2
Views: 640
Reputation: 60026
You are missing a part in your loop from your explication your lines is like :
firstname1 familyname1
firstname2 familyname2
So after you split you can easily use :
for (String strLine : data) {
String[] strWord = strLine.split("[\\s']");
splitdata.add(strWord[0] + "." + strWord[1] + "@mail.com");
//------------first name last name
}
System.out.println(splitdata);
Output :
[[email protected], [email protected]]
Note you have to verify your names before you use them, what if the name have many parts, also you have to use the right delimiter between the names.
Upvotes: 1
Reputation: 2052
After reading data you can create an 2d array and store first and last name there and then concatenate them to create an email address as you asked for.
String[][] splitdata = new String[data.size()][2];
int rowNum = 0;
for (String strLine : data) {
String[] strWord = strLine.split("[\\s]");
// Store it in an array as you asked for or join them right here
splitdata[rowNum][0] = strWord[0];
splitdata[rowNum][1] = strWord[1];
++rowNum;
}
for (String[] row: splitdata) {
System.out.println(row[0] + "." + row[1] + "@mail.com");
}
If you are using java8 the whole thing as be written as..
Path path = Paths.get("D:\\NetbeansProjects\\Emails\\src\\emails\\lijst.txt");
String commaJoinedEmails = String.join(",", Files.lines(path)
.map(line -> line.split("\\s"))
.map(tokens -> tokens[0] + "." + tokens[1] + "@mail.com")
.toArray(String[]::new));
Upvotes: 1
Reputation: 55
I would suggest you to read the file line by line.
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
This is the most common way of doing it. In the current line parameter you will store the first and family names and after that you can process the two names (preferably with a StringBuffer) and add the result to the final string of your choice.
Good luck :)
Upvotes: 1