java 从文本文件中读取数据并使用数组构建表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27285808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:33:35  来源:igfitidea点击:

Reading data from a text file and building a table with arrays

javaarraysio

提问by Stacker11

I have an input file named "animals.txt":

我有一个名为“animals.txt”的输入文件:

sheep 10.5 12.3 4
horse 8.4  11.2 7
cow   13.7 7.2  10
duck  23.2 2.5  23
pig   12.4 4.6  12

To put my question simply, I would like to know how to store the 4 columns of data into 4 separate 1 dimensional arrays from the input file.

简单地说,我想知道如何将 4 列数据从输入文件存储到 4 个单独的一维数组中。

The output should like something like this...

输出应该像这样......

[sheep, horse, cow, duck, pig]
[10.5, 8.4, 13.7, 23.2, 12.4]
[12.3, 11.2, 7.2, 2.5, 4.6]
[4, 7, 10, 23, 12]

So far I have figured out how to store all of the data into one large array, but I need to know how to break it down and store each column into its own array instead.

到目前为止,我已经弄清楚如何将所有数据存储到一个大数组中,但我需要知道如何将其分解并将每一列存储到自己的数组中。

My code:

我的代码:

public static void main(String[] args) throws FileNotFoundException {

    String[] animal = new String[5];
    int index = 0;

    File file = new File("animals.txt");
    Scanner input = new Scanner(file);

    while (input.hasNextLine() && index < animal.length) {
        animal[index] = input.nextLine();
        index++;
    }

回答by Shadow

You could use an array of arrays to store what you need, like:

您可以使用一组数组来存储您需要的内容,例如:

String[][] animal = new String[5][];

Then, when you read your file, store an array of all the values, like this:

然后,当您读取文件时,存储所有值的数组,如下所示:

while (input.hasNextLine() && index < animal.length) {
    animal[index] = input.nextLine().split(" "); //split returns an array
    index++;
}

Then, when you want to output, just loop over the array of arrays:

然后,当你想输出时,只需循环数组数组:

for (String[] a : animal)
{
    for (int i = 0; i < a.length; i++)
        System.out.print(a[i] + ", ");
    System.out.println("");
}

回答by Shadow

Below is code for a way to do it - you can cut and paste it into a java project in an IDE like eclipse and run it or put it in a file.java and compile and run it on the command line. Next step would be to make it fully general to take any input including lines with variable number of columns with no predetermined max and without reading the input file twice or storing it memory as an array or other object.

下面是一种实现方法的代码 - 您可以将其剪切并粘贴到 Eclipse 等 IDE 中的 Java 项目中并运行它,或将其放入 file.java 并编译并在命令行上运行它。下一步是使其完全通用,包括具有可变列数的行,没有预先确定的最大值,并且不读取输入文件两次或将其存储为数组或其他对象。

import java.io.File;
import java.io.FileNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class BuildTableWithArrays {

    private static final String separator = "\s+"; // regex for parsing lines
    private static final int rowWidth = 4;

    public static void main(String[] args) {

        Map<Integer, ArrayList<String>> columns = buildMapWithColumnArrayLists("animals.txt");
        printMap(columns);  // for demo
        // if you want actual arrays
        Map<Integer, String[]> colArrays = buildMapWithColumnArrays(columns);

    }

    public static Map<Integer, ArrayList<String>> buildMapWithColumnArrayLists(
        String fileName) {

        ArrayList<String> col0 = new ArrayList<String>();
        ArrayList<String> col1 = new ArrayList<String>();
        ArrayList<String> col2 = new ArrayList<String>();
        ArrayList<String> col3 = new ArrayList<String>();

        Map<Integer, ArrayList<String>> columns = new HashMap<Integer, ArrayList<String>>();
        columns.put(0, col0);
        columns.put(1, col1);
        columns.put(2, col2);
        columns.put(3, col3);

        File file = new File(fileName);
        try {
            Scanner input = new Scanner(file);
            while (input.hasNextLine()) {
                String[] line = input.nextLine().trim().replaceAll(separator, " ")
                    .split(separator);
                for (int i = 0; i < rowWidth; i++) {
                    if (line[i] == null) {
                        columns.get(Integer.valueOf(i)).add("null");
                    } else {
                        columns.get(Integer.valueOf(i)).add(line[i]);
                    }
                }
            }
            input.close();
        } catch (FileNotFoundException x) {
            System.out.println(x.getMessage());
        }

        return columns;
    }

    public static void printMap(Map<Integer, ArrayList<String>> columns) {

        for (int i = 0; i < rowWidth; i++) {
            System.out.println("col" + i + " #elements = "
                + columns.get(Integer.valueOf(i)).size());
            for (String s : columns.get(Integer.valueOf(i))) {
                System.out.print(s + " ");
            }
            System.out.println("\n");
        }
    }

    public static String[] convertArrayList2Array (ArrayList<String> arrayList) {

        String[] array = new String[arrayList.size()];
        array = arrayList.toArray(array);
        return array;

    }

    public static Map<Integer, String[]> buildMapWithColumnArrays(Map<Integer, ArrayList<String>> columns) {

        Map<Integer, String[]> cols = new HashMap<Integer, String[]>(); 

        for (Map.Entry<Integer, ArrayList<String>> entry : columns.entrySet()) {
            Integer key = entry.getKey();
            ArrayList<String> value = entry.getValue();
            String[] val = convertArrayList2Array(value);
            cols.put(key,val);
        }

        return cols;

    }

}

回答by Vincent Ramdhanie

If the structure of your input file is guaranteed then you can use the scanner to get the data that you need. Start by declaring the 4 arrays that you want with appropriate types.

如果您的输入文件的结构得到保证,那么您可以使用扫描仪来获取您需要的数据。首先用适当的类型声明您想要的 4 个数组。

Then in your while loop use:

然后在你的 while 循环中使用:

  input.next()

to get a string

得到一个字符串

  input.nextInt()

to get an integer and

得到一个整数和

  input.nextDouble()

to get a double value. Of course you assign these values to the appropriate array.

获得双重价值。当然,您将这些值分配给适当的数组。