import java.io.*; import java.util.*; import java.util.regex.*; class ParseEmail2 { public static void main(String[] args) throws IOException { Reader r = new BufferedReader(new FileReader("message1.txt")); Scanner message = new Scanner(r); String line, field, value; int pos; Pattern leadingWhitespace = Pattern.compile("\\A[ \t]+"); Matcher m; // read headers while ( message.hasNextLine() ) { line = message.nextLine(); if ( line.length()==0 ) { // end of headers break; } if ( Pattern.matches("\\A\\s+.*", line) ) { // continuation line System.out.println("continuation"); // should do something better here: add it to the string, say. } else { // new header pos = line.indexOf(":"); field = line.substring(0, pos); value = line.substring(pos+1); m = leadingWhitespace.matcher(value); value = m.replaceFirst(""); System.out.println(field); System.out.println(value); } } // read message body while ( message.hasNextLine() ) { line = message.nextLine(); // do something with each line... } } }