从Java中的File中读取一定数量的元素

时间:2017-11-30 16:59:07

标签: java file io

我的文本文件中包含少量数字;

10 20 30 40 50

我的座右铭是一次读取3个数字并对其进行一些操作。 请帮助我学习完成这项工作的最佳方法。

我需要以这种方式处理数字,

10 20 30

20 30 40

30 40 50 .....

如果我的文本文件有一行包含100000个数字,建议将整个文件加载到内存中并保持遍历和执行操作,还是将整个行复制到数组中并对其执行操作是否合适?

3 个答案:

答案 0 :(得分:1)

这是一种简单的方法:

    int a, b, c;

    // try with resources, scanner will be closed when we are done.
    try (Scanner scan = new Scanner(new File("input.txt"))) {
        // get the first three ints.
        a = scan.nextInt();
        b = scan.nextInt();
        c = scan.nextInt();
        doSomething(a, b, c);
        // while there are more
        while (scan.hasNext()) {
            a = b;
            b = c;
            c = scan.nextInt();
            doSomething(a, b, c);
        }

    } catch (FileNotFoundException | NoSuchElementException e) {
        e.printStackTrace();
    }

这将一次读取一个数字,并在每次读取之间执行一些操作。

如果要在执行操作之前读取所有数字,可以使用数组列表。

    ArrayList<Integer> list = new ArrayList<>();
    // try with, scanner will be closed when we are done.
    try (Scanner scan = new Scanner(new File("input.txt"))) {
        // while there are more
        while (scan.hasNext()) {
            list.add(scan.nextInt());
        }

    } catch (FileNotFoundException | NoSuchElementException e) {
        e.printStackTrace();
    }

然后你可以迭代它们。

    for (int i : list) {

    }

如果您知道有多少个数字,那么使用IntBuffer代替ArrayList会有效。

对于只有100000个值,如果您根据需要加载它们或首先加载它们,它可能没什么区别。如果您的操作需要很长时间,那么最好全部加载它们。

答案 1 :(得分:0)

嗯,这取决于你想要什么。将所有数字加载到内存将花费更多时间,但使用内存中的数字的操作将更快。如果你不想分配一个&#34;大&#34;你的记忆的一部分,以保存你可以读取文件的所有数字,同时进行操作。虽然,它不会有太大的区别,因为文件只保存数字,它的大小不会很大。

下面是一个可以实现您想要的代码示例。

完整代码

public static void main (String args[]){

    //Scanner will read your file
    Scanner scanner = null;
    try {
        scanner = new Scanner(new File("file.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    // tmpInts will old the tmp values that are read
    int [] tmpInts = new int[3];
    // Holds a controller to know if we can do the operation
    int i = 0;

    while(scanner.hasNextInt()){

        // Do the operation only when tmpInts has 3 numbers inside it
        if(i > 2){

            System.out.println("Read: ["+tmpInts[0] +" "+ tmpInts[1] +" "+ tmpInts[2]+"] Sum: "+(tmpInts[0] + tmpInts[1] + tmpInts[2]));
            shiftInts(tmpInts);

            tmpInts[2] = scanner.nextInt(); // Read next number

        } else {
            tmpInts[i] = scanner.nextInt(); // Read next number
            i++;
        }
    }

    // Check if there are at least 3 numbers in the file
    // If not, don't do the operation
    // If yes, this is the last operation call to handle the last state of tmpInts array
    if(!isEmpty(tmpInts))
        System.out.println("Read: ["+tmpInts[0] +" "+ tmpInts[1] +" "+ tmpInts[2]+"] Sum: "+(tmpInts[0] + tmpInts[1] + tmpInts[2]));

    scanner.close(); // IMPORTANT! Don't forget to close your scanner

}

// Shift numbers one index left to put a third one in the last index of the array after
public static void shiftInts(int[] tmpInts) {
    tmpInts[0] = tmpInts[1];
    tmpInts[1] = tmpInts[2];
}

// Check if array is full. If it is not it means that your file doesn't have at least 3 numbers. i choosed 0 as default value in array, you can choose another one that won't appear in your file
public static boolean isEmpty(int[] tmpInts) {
    for(int i: tmpInts){
        if(i == 0){
            return true;
        }
    }

    return false;
}

希望它有所帮助!

答案 2 :(得分:0)

我将line作为String并转换为整数数组,以将所有数字加载到内存中。我们可以通过迭代对整数数组进行必要的操作。

以下是示例代码:

public static void main(String[] args) {

    String fileName = "temp1.txt";
    String line;

    try {
        FileReader fileReader = new FileReader(fileName);

        BufferedReader bufferedReader = new BufferedReader(fileReader);


        while ((line = bufferedReader.readLine()) != null) {

            String[] inputNumbers = line.split(",");
            int numbers[] = new int[inputNumbers.length];
            for (int i = 0; i < inputNumbers.length; i++) {
                numbers[i] = Integer.parseInt(inputNumbers[i]);
                                }
            for (int j = 0; j < numbers.length - 2; j++) {
                int sum = numbers[j] + numbers[j + 1] + numbers[j + 2];
                System.out.println(sum);
            }


        }

        bufferedReader.close();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();


    } catch (IOException ex) {


        ex.printStackTrace();
    }

}

}