.replaceAll和换行符的java问题

时间:2014-01-29 01:41:26

标签: java javamail replaceall

所以这段代码按预期工作:

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

输出:

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

但我正在阅读一封带有javamail的电子邮件,出于某种原因,当我查看该消息时,它有一堆新行。但由于某种原因,replaceAll(“\ n”,“”)对我不起作用。我想知道这是编码问题还是其他问题。还有另一种方法可以换行吗?当我查看gmail下的电子邮件时,它似乎没有任何新行,但是当我打印出来或尝试导出消息时,任何超过70个字符的行都会被分割到单词边界。有什么想法吗?

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

输出:

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.

1 个答案:

答案 0 :(得分:3)

似乎行未使用\n分隔,而是\r\n。考虑使用

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

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

也接受\r\n \n \r