📜  如何在java代码示例中从文本文件中读取表格

📅  最后修改于: 2022-03-11 14:52:32.250000             🧑  作者: Mango

代码示例1
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> columns = buildMapWithColumnArrayLists("animals.txt");
        printMap(columns);  // for demo
        // if you want actual arrays
        Map colArrays = buildMapWithColumnArrays(columns);

    }

    public static Map> buildMapWithColumnArrayLists(
        String fileName) {

        ArrayList col0 = new ArrayList();
        ArrayList col1 = new ArrayList();
        ArrayList col2 = new ArrayList();
        ArrayList col3 = new ArrayList();

        Map> columns = new HashMap>();
        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> 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 arrayList) {

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

    }

    public static Map buildMapWithColumnArrays(Map> columns) {

        Map cols = new HashMap(); 

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

        return cols;

    }

}