Question

So this code works as expected:

String test = "ONE: this is a\ntest string.";
System.out.println(test);
test = test.replaceAll("\n", " ");
System.out.println(test);

output:

ONE: this is a 
test string.
ONE: this is a test string.

But I am reading in an email with javamail and for some reason when I look at the message it has a bunch of newlines in it. But for some reason replaceAll("\n"," ") isn't working for me. I wonder if it is an encoding issue or something. Is there another way to have a newline? When I look at the email under gmail it doesn't seem to have any newlines but when I print it out or try to export the message then any line with more than about 70 characters gets split up on a word boundary. Any ideas?

Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "xxx@gmail.com", "password");

Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_WRITE);
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message messages[] = inbox.search(ft);
for(Message msg:messages) {
    String message = mailman.getContent(msg);
    System.out.println("ONE:"+ message);
    message = message.replaceAll("\n","");
    System.out.println("TWO:  "+message);
}

output:

ONE: We just wanted to remind you about the start of our Underclassmen Academy. 
This program is intended for all freshmen and sophomores who are in the 
initial stages of your career preparation. Juniors are also invited to attend 
if you'd like to gain more exposure and/or are still recruiting.

TWO: We just wanted to remind you about the start of our Underclassmen Academy. 
This program is intended for all freshmen and sophomores who are in the 
initial stages of your career preparation. Juniors are also invited to attend 
if you'd like to gain more exposure and/or are still recruiting.
Was it helpful?

Solution

It seems that lines are not separated with \n but with \r\n. Consider using

replaceAll("\r\n"," ")

or

replaceAll("\r?\n|\r"," ")

to accept also \r\n \n \r.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top