繁体   English   中英

如何合并N个排序两个文本文件

[英]How to Merge N sort two text files

我必须阅读两个看起来像这样的文本文件。

FileOne:10 1 2 3 4 5 67 75 47 18

FileTwo:5 65 74 57 68 28 38

第一个数字表示我应使用多少个整数来填充数组。

我需要读取文件的第一行,然后使用该数字用指定的许多元素填充两个数组。

我已经弄清楚了如何读取两个文本文件并将它们连接在一起,但是我无法弄清楚如何仅从文件中获取第一个数字并用它来确定之后应该使用多少个数字。

import java.io.File;
import java.util.Arrays;
import java.util.Scanner;


public class ReadData {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Please enter the first file name: ");
        String input = s.nextLine();
        System.out.println("Please enter the second file name: ");
        String input2 = s.nextLine();

        int[] data = readFiles(input);
        int[] data2 = readFiles(input2);
        //System.out.println(Arrays.toString(data));
        //System.out.println(Arrays.toString(data2));
        System.out.println(Arrays.toString(concat(data, data2)));
    }   

    public static int[] readFiles(String file) {

        try {

            File f = new File(file);
            Scanner s = new Scanner(f);
            int counter = 0;
            while(s.hasNextInt()) {
                counter++;
                s.nextInt();
            }
            int[] arr = new int[counter];

            Scanner s1 = new Scanner(f);

            for(int i = 0; i < arr.length; i++)
                arr[i] = s1.nextInt();

            return arr;
        }
        catch(Exception e) {
            return null;
        }   
    }
    static int[] concat(int[]... arrays) {
    int length = 0;
    for (int[] array : arrays) {
        length += array.length;
    }
    int[] result = new int[length];
    int pos = 0;
    for (int[] array : arrays) {
        for (int element : array) {
            result[pos] = element;
            pos++;
        }
    }
    return result;
}
}

对于初学者,我建议将整个行作为单个字符串读取,然后使用解析器解析它,它将使用空格作为定界符。 您将获得一个包含所有数字的DS,这是一种更为优雅的解决方案。 (Java解析简单解决方案: http : //pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString.html

一旦您拥有包含数字的DS,便可以在上面愉快地进行迭代,记住第一个值确定了DS上将来的迭代次数。

假设您使用的是Java 8,我建议您使用流功能来这样做: http : //winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/

如果需要任何详细说明和好运,请发表评论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM