读取txt文件并将每个列添加到java中的不同数组

时间:2017-02-27 20:16:30

标签: java android arrays swing

我的txt文件如下所示:

1,2,6,8,10,3
0,3,5,0
0,1
1,6,90,6,7

我正在阅读txt文件。但我想为每列创建数组。 enter image description here

例如:

array0将包含:1,2,6,8,10,3

array1将包含:0,3,5,0

我怎么能这样做?

我的代码:

File file = new File("src/maze.txt");
 try (FileInputStream fis = new FileInputStream(file)) {
        // Read the maze from the input file

        ArrayList column1array = new ArrayList (); 
        ArrayList column2array = new ArrayList (); 
        while ((content = fis.read()) != -1) {
            char c = (char) content;

            column1array.add(c);

        }
     }

2 个答案:

答案 0 :(得分:1)

您可以使用BufferedReader,阅读每一行文件split并将其转换为integer数组。

此外,您可以声明integer数组的列表,并在处理新行时将值添加到其中。下面是一个示例代码:

public static void main(String[] args) throws Exception {
    File file = new File("src/maze.txt");
    List<Integer[]> columns = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
        // Read the maze from the input file
        String line;
        while((line = reader.readLine()) != null){
            String[] tokens = line.split(",");
            Integer[] array = Arrays.stream(tokens)
                    .map(t -> Integer.parseInt(t))
                    .toArray(Integer[]::new);
            columns.add(array);
        }
    }
}

答案 1 :(得分:1)

我认为你的意思是行而不是列。

如果行数是动态的,则应使用initializer_list readline()方法读取文件行。

对于每个读取行,您应该使用BufferedReader字符将其拆分以存储每个数字值。 您可以在特定列表中存储行的标记。

您可以将所有列表存储在列表中。

我在你的例子中引用了一个,,你使用了一个List,并且按行显示的元素数量似乎在变化。所以列表似乎更合适。

java.util.List