【问题标题】:read txt file and add each column to different array in java读取txt文件并将每一列添加到java中的不同数组中
【发布时间】:2017-02-27 20:16:30
【问题描述】:

我的 txt 文件是这样的:

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

我正在阅读 txt 文件。但我想为每一列创建数组。

例如:

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);

        }
     }

【问题讨论】:

    标签: java android arrays swing


    【解决方案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);
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

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

      如果行数是动态的,你应该使用BufferedReaderreadline()方法逐行读取文件。

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

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

      我指的是java.util.List,因为在您的示例中,您使用了 List 并且每行的元素数似乎在变化。所以列表似乎更可取。

          List<List<Integer>> listOfList = new ArrayList<List<Integer>>();
      
          try (BufferedReader fis = new BufferedReader(new FileReader(file))) {
      
              String line = null;
              while ((line = fis.readLine()) != null) {
                  ArrayList<Integer> currentList = new ArrayList<>();
                  listOfList.add(currentList);
                  String[] values = line.split(",");
                  for (String value : values) {
                      currentList.add(Integer.valueOf(value));
                  }
              }
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-23
        相关资源
        最近更新 更多