public static HostsFileEntries parse ( Reader reader ) throws IOException { checkNotNull ( reader , "reader" ) ; BufferedReader buff = new BufferedReader ( reader ) ; try { Map < String , Inet4Address > ipv4Entries = new HashMap < String , Inet4Address > ( ) ; Map < String , Inet6Address > ipv6Entries = new HashMap < String , Inet6Address > ( ) ; String line ; while ( ( line = buff . readLine ( ) ) != null ) { // remove comment int commentPosition = line . indexOf ( ' ' ) ; if ( commentPosition != - 1 ) { line = line . substring ( 0 , commentPosition ) ; } // skip empty lines line = line . trim ( ) ; if ( line . isEmpty ( ) ) { continue ; } // split List < String > lineParts = new ArrayList < String > ( ) ; for ( String s : WHITESPACES . split ( line ) ) { if ( ! s . isEmpty ( ) ) { lineParts . add ( s ) ; } } // a valid line should be [IP, hostname, alias*] if ( lineParts . size ( ) < 2 ) { // skip invalid line continue ; } byte [ ] ipBytes = NetUtil . createByteArrayFromIpAddressString ( lineParts . get ( 0 ) ) ; if ( ipBytes == null ) { // skip invalid IP continue ; } // loop over hostname and aliases for ( int i = 1 ; i < lineParts . size ( ) ; i ++ ) { String hostname = lineParts . get ( i ) ; String hostnameLower = hostname . toLowerCase ( Locale . ENGLISH ) ; InetAddress address = InetAddress . getByAddress ( hostname , ipBytes ) ; if ( address instanceof Inet4Address ) { Inet4Address previous = ipv4Entries . put ( hostnameLower , ( Inet4Address ) address ) ; if ( previous != null ) { // restore, we want to keep the first entry ipv4Entries . put ( hostnameLower , previous ) ; } } else { Inet6Address previous = ipv6Entries . put ( hostnameLower , ( Inet6Address ) address ) ; if ( previous != null ) { // restore, we want to keep the first entry ipv6Entries . put ( hostnameLower , previous ) ; } } } } return ipv4Entries . isEmpty ( ) && ipv6Entries . isEmpty ( ) ? HostsFileEntries . EMPTY : new HostsFileEntries ( ipv4Entries , ipv6Entries ) ; } finally { try { buff . close ( ) ; } catch ( IOException e ) { logger . warn ( "Failed to close a reader" , e ) ; } } }
Parse a reader of hosts file format .