2017-03-12 103 views
-3

我正在嘗試將二維數組寫入文本文件,但以一種顯示每行起始行號的方式因爲在打印到文件的每個值之前都有一個單詞。例如,我希望程序編寫每個元素,例如ItemNo,後跟數組元素中包含的值。如下圖所示:在每個打印數組值之前打印具有行號和單詞的二維數組的內容

Row 1: ItemNo3 ItemNo5 ItemNo8 
Row 2: ItemNo9 ItemNo10 ItemNo12 
Row 3: ItemNo15 ItemNo17 ItemNo18 

我在我的屏幕一直盯着一段時間了,只是不能讓我的腦袋解決這個問題。任何幫助,將不勝感激!

回答

0

試試這個代碼:

int[][] arr = new int[3][3]; 

     //fill array 
     for(int i = 0; i < arr.length; i++) { 
      for(int j = 0; j < arr[0].length; j++) { 
       arr[i][j] = j; 
      } 
     } 

     //create path 
     Path path = Paths.get("your\\path\\to\\file"); 

     try { 
      //check if file exists; if not, create it 
      if(!(new File(path.toString()).exists())) { 
       Files.write(path, ("").getBytes()); 
      } 

      int row = 1; 
      //iterate through the 2D array 
      for(int[] a : arr) { 
       //write the row number 
       Files.write(path, ("Row" + row + ": ").getBytes(), StandardOpenOption.APPEND); 
       for(int val : a) { 
        //write the ItemNo 
        Files.write(path, ("ItemNo" + val + " ").getBytes(), StandardOpenOption.APPEND); 
       } 
       row++; 
       //write a newline 
       Files.write(path, (System.getProperty("line.separator")).getBytes(), StandardOpenOption.APPEND); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     }