簡體   English   中英

讀取txt文件並將每一列添加到Java中的不同數組

[英]read txt file and add each column to different array in java

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

        }
     }

您可以使用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);
        }
    }
}

我認為您的意思是行而不是列。

如果行數是動態的,則應使用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));
            }
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM