在文件

时间:2015-06-10 00:49:43

标签: java file add

我有一个包含大量文件的目录(~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;
    }
}

3 个答案:

答案 0 :(得分:1)

这正是您所需要的。 它将动态检查所有文件,您不需要提供多少文件。 例如,如果每个文件中有任意数量的文件和不同的行数,请不要担心。它会正确读取。

import java.io.*;
import java.util.*;
import java.text.*;

public class TicTacToeCounter
{
    //arraylist that will read and hold all file names that can be used later in the program.
    public ArrayList<String> fileList = new ArrayList<String>();
    //arraylist of all lines from all files.
    ArrayList<Integer> theData = new ArrayList<Integer>();

    //class constructor
    public TicTacToeCounter() throws Exception
    {
        //provide the directory name here where you have those 40000 files.
        //I have testdata directory in my program in the same folder where my .java and .class file resides.
        File folder = new File("testdata");
        File[] listOfFiles = folder.listFiles();
        ArrayList<String> tempData = new ArrayList<String>();

        for (int i = 0; i < listOfFiles.length; i++)
        {
            if (listOfFiles[i].isFile())
            {
                fileList.add(listOfFiles[i].getName());
            }
            else if (listOfFiles[i].isDirectory())
            {
                System.out.println("Directory " + listOfFiles[i].getName());
            }
        }

        //for every filename in fileList, do....
        for (String s : fileList)
        {
            //call readFile method and pass file name as a variable s. add objects to tempData arraylist.
            tempData = readFile(s);
            //for every line in tempData, do....
            for (String line : tempData)
            {
                //add the line in theData arraylist, also convert into Integer before adding.
                theData.add(Integer.parseInt(line));
            }
        }

        //for every object in theData arraylist, print the object. alternatevely you can print it in previous stage.
        for (Integer s : theData)
        {
            System.out.println(s);
        }
    }

    //readFile method that will read our data files.
    public ArrayList<String> readFile(String fileName) throws Exception
    {
        ArrayList<String> data = new ArrayList<String>();
        //don't forget to add directory name here as we are only passing filename, not directory.
        BufferedReader in = new BufferedReader(new FileReader("testdata/"+fileName));

        String temp = in.readLine(); 
        while (temp != null)
        {
            data.add(temp);
            temp = in.readLine(); 
        }
        in.close();
        return data;
    }
}

答案 1 :(得分:0)

堆栈跟踪应该告诉您错误发生的确切位置的行号,并且您不必猜测。请检查:目录是否存在且它是一个目录,并且在对其执行长度之前,listOfFiles不为null。

folder.exists() && folder.isDirectory() {
   \\ you might want to check if folder.canRead() and folder.canWrite()
   \\ get listOfFiles
}

if (listOfFiles != null) { // proceed with operations

P.S:你的getWins和getLosses也可以改进。我可能会尝试一次读取文件(并创建如果那些文件不存在,如果必须,但是如同@sstan提到的那样,你只是从目录中获得文件名,没有理由不应该这样做&#39 ; t存在)并且如果文件中始终只有2行,则读取胜负。现在,你正在创建一个如果它不存在并且正在阅读你刚刚创建的那个,我们不必这样做。

答案 2 :(得分:-1)

不使用Data for Array,而是使用ArrayList。让您了解错误发生的原因是更方便和透明的。而且,如果你使用数组,你必须在启动它时定义一个长度,在你的情况下你还没有完成。