【发布时间】:2015-06-10 00:49:42
【问题描述】:
我有一个包含很多文件(约 40,000 个)的目录,每个文件正好有两行,每行都有一个数字。我想将整个目录中的所有数字相加;我如何快速有效地做到这一点?
我试过这个,但它不起作用,我一生都无法弄清楚为什么。我得到一个 NullPointerException,但它不应该是,因为我猜是 listOfFiles.length 导致它。
package me.counter;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class TicTacToeCounter {
static String dir = "./data/";
public static void main(String args[]) throws IOException{
int total = 0;
File folder = new File(dir);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
total += getWins(listOfFiles[i].getAbsolutePath());
total += getLosses(listOfFiles[i].getAbsolutePath());
}
System.out.println(total);
}
public static int getWins(String move) throws IOException{
File f = new File(move);
if(!f.exists()){
f.createNewFile();
PrintWriter writer = new PrintWriter(move, "UTF-8");
writer.println("0");
writer.println("0");
writer.close();
return 0;
}
Scanner fscanner = new Scanner(f);
int wins = 0;
if(fscanner.hasNext())
wins = fscanner.nextInt();
fscanner.close();
return wins;
}
public static int getLosses(String move) throws IOException{
File f = new File(move);
if(!f.exists()){
f.createNewFile();
PrintWriter writer = new PrintWriter(move, "UTF-8");
writer.println("0");
writer.println("0");
writer.close();
return 0;
}
Scanner fscanner = new Scanner(f);
fscanner.nextInt();
int losses = 0;
if(fscanner.hasNext())
losses = fscanner.nextInt();
fscanner.close();
return losses;
}
}
【问题讨论】:
-
尝试一下。如果您有具体问题,请发布您的尝试并编辑您的问题。
-
@paisanco 我添加了我的代码
-
I'm guessing that the listOfFiles.length:你不需要猜测。请发布您的确切错误消息以及完整的堆栈跟踪,包括行号,我们会确定的。 -
@sstan 我收到一条消息说错误来自第 15 行,这也是 listOfFiles.length 所在的位置。