我有一个文本文件,该列表包含5000个名称,名称是“男”(“ MO”)还是仅女(“ FO”)还是“男”和“女”(“ MF”),其格式都如此。
FO ABBY
MO ABDUL
MO ABE
MO ABEL
FO ABIGAIL
我想使用可调用对象,然后返回文件中有多少个“ FO”,“ MO”和“ MF”,并将返回值存储在将来的列表中,然后将其输出到屏幕。
我期望以下输出:
MF-331
MO-0
FO-3944
如何调用同时计算的多个可调用对象。我对于“ FO”一无所获,大多数名称是“ FO”。
期望的结果应该像这样分发。
MF-500
MO-1500
FO-3000
我是多线程技术的新手,所以我不确定自己做错了什么。如果您能指出正确的方向,我将不胜感激
public class ParsingTextFile {
/**Main method
* @throws InterruptedException
* @throws ExecutionException */
public static void main(String[] args) throws InterruptedException, ExecutionException {
// Declare file reader and writer streams
String code = null ;
List<Callable<Integer>> callables = Arrays.asList(
callable("MF",ThreadLocalRandom.current().nextInt(1, 5 + 1)),
callable("MO",ThreadLocalRandom.current().nextInt(1, 5 + 1)),
callable("FO",ThreadLocalRandom.current().nextInt(1, 5 + 1))
);
// Process a record
ExecutorService exe = Executors.newCachedThreadPool();
List<Future<Integer>> arr = exe.invokeAll(callables);
for (Future<Integer> s : arr) {
System.out.println(s.get());
}
exe.shutdownNow();
}
static Callable<Integer> callable(String result, long sleepSeconds) {
return () -> {
int count = 0;
FileReader frs = null;
FileWriter fws = null;
// Declare streamTokenizer
StreamTokenizer in = null;
// Declare a print stream
PrintWriter out = null;
try {
// Create file input and output streams
frs = new FileReader("census.txt");
// Create a stream tokenizer wrapping file input stream
in = new StreamTokenizer(frs);
// Read first token
in.nextToken();
while (in.ttype != StreamTokenizer.TT_EOF) {
// Get student name
if (in.ttype == StreamTokenizer.TT_WORD)
{
String val = in.sval;
if (val.equals("MF") && result == "MF")
{
count++;
}
else if(val.equals("MO") && result == "M0")
{
count++;
}
else if(val.equals("FO") && result == "FO")
{
count++;
}
}
else
System.out.println("Bad file format");
in.nextToken();
}
}
catch (FileNotFoundException ex) {
System.out.println("File not found: census.text");
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
finally {
try {
if (frs != null) frs.close();
if (fws != null) fws.close();
}
catch (IOException ex) {
System.out.println(ex);
}
}
return count;
};
}