I have a directory with a lot of files (~40,000), and each file has exactly two lines, each with a number. I want to add up all of the numbers in the entire directory; how do I do that fast and efficiently?
I tried this, but it doesn't work, and I can't figure out for the life of me why. I get a NullPointerException, but it shouldn't be, since I'm guessing that the listOfFiles.length is causing it.
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;
}
}
This is exactly what you need. It will check all files dynamically, you don't need to give number of files. for example, if you have any number of files and various number of rows in each file, not to worry. it will read it correctly.