Есть много способов сделать это;другие упоминали, что java.util.Properties
выполняет большую часть работы и, вероятно, является наиболее надежным решением.
Еще один вариант - использовать java.util.Scanner
.
Вот пример, который сканирует String
для простоты:
String text =
"#Hi, this is a sample file.\n" +
"\n" +
"\"abcd\" = 12; \r\n" +
"\"abcde\"=16;\n" +
" # \"ignore\" = 13;\n" +
"\"http\" = 32; # Comment here \r" +
"\"zzz\" = 666; # Out of order! \r" +
" \"sip\" = 21 ;";
System.out.println(text);
System.out.println("----------");
SortedMap<String,Integer> map = new TreeMap<String,Integer>();
Scanner sc = new Scanner(text).useDelimiter("[\"=; ]+");
while (sc.hasNextLine()) {
if (sc.hasNext("[a-z]+")) {
map.put(sc.next(), sc.nextInt());
}
sc.nextLine();
}
System.out.println(map);
Это печатает (, как видно на ideone.com ):
#Hi, this is a sample file.
"abcd" = 12;
"abcde"=16;
# "ignore" = 13;
"http" = 32; # Comment here
"zzz" = 666; # Out of order!
"sip" = 21 ;
----------
{abcd=12, abcde=16, http=32, sip=21, zzz=666}
Смежные вопросы
См. Также