2017-02-27 41 views
1

我的txt文件看起來像:閱讀txt文件,每一列在java中添加不同的陣列

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

我讀txt文件。但我想爲每列創建數組。 enter image description here

例如:

陣列0將包含:1,2,6,8,10,3

陣列1將包含: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); 

     } 
    } 

回答

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); 
     } 
    } 
} 
+0

謝謝Dershan –

1

我認爲你的意思是行而不是列。

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

    } 
+0

謝謝 –

+0

歡迎您:) – davidxxx