java parsefile,什么是用Java解析文件的最佳方法 (Whats the best way to parse a file in Java)...

There are many ways to do this; others have mentioned that java.util.Properties gets most of the job done, and is probably the most robust solution.

One other option is to use a java.util.Scanner.

Use the Scanner(File) constructor to scan a file

You can useDelimiter appropriate for this format

nextInt() can be used to extract the numbers

Perhaps you can put the key/value pairs into a SortedMap

Here's an example that scans a String for simplicity:

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 map = new TreeMap();

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

#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}

Related questions

See also

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值