文件:
Person1:AP
Person2:AP
Person3:KE
Person4:KE
Person5:UK
Person6:AP
Person7:UK
Person8:AP
我尝试过的是:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
public class TestNull {
public static void main ( String args[]) throws IOException {
BufferedReader br = new BufferedReader ( new FileReader("/home/username/Desktop/test"));
String str;
HashMap<String, String> h = new HashMap<String, String>();
try {
while ( (str = br.readLine()) != null) {
String[] s = str.split(":");
h.put(s[1],s[0]);
}
System.out.println(h);
}
catch (FileNotFoundException E) {
System.out.println("File Not Found");
}
finally {
br.close();
}
}
}
我可以通过 Perl 实现这一点:
use strict;
use warnings;
open (FILE,"test");
my %hash=();
while (my $line = <FILE>) {
chomp $line;
my ($name,$country) = split(":", $line);
chomp ($name,$country);
$hash{$country} .= "$name ";
}
for my $keys (keys %hash) {
print "$keys: $hash{$keys}\n";
}
从数据文件中,我正在寻找这样的输出:
{AP = [person1, person 2, person6, person8], KE = [person3, person4], UK = [person5, person7]}