2011-03-25 72 views

回答

2

此代碼序列化INT陣列和反序列化迴轉換成int數組

private static final char NEXT_ITEM = ' '; 

public static void main(String[] args) throws IOException { 
    int[][] twoD = new int[][] { new int[] { 1, 2, 2, 4, 4 }, new int[] { 3, 4, 0 }, new int[] { 9 } }; 

    int[][] newTwoD = null; // will deserialize to this 

    System.out.println("Before serialization"); 

    for(int[] arr : twoD) { 
     for(int val : arr) { 
      System.out.println(val); 
     } 
    } 

    String str = serialize(twoD); 

    System.out.println("Serialized: [" + str + "]"); 

    newTwoD = deserialize(str); 

    System.out.println("After serialization"); 

    for(int[] arr : newTwoD) { 
     for(int val : arr) { 
      System.out.println(val); 
     } 
    } 
} 

private static String serialize(int[][] array) { 
    StringBuilder s = new StringBuilder(); 
    s.append(array.length).append(NEXT_ITEM); 

    for(int[] row : array) { 
     s.append(row.length).append(NEXT_ITEM); 

     for(int item : row) { 
      s.append(String.valueOf(item)).append(NEXT_ITEM); 
     } 
    } 

    return s.toString(); 
} 

private static int[][] deserialize(String str) throws IOException { 
    StreamTokenizer tok = new StreamTokenizer(new StringReader(str)); 
    tok.resetSyntax(); 
    tok.wordChars('0', '9'); 
    tok.whitespaceChars(NEXT_ITEM, NEXT_ITEM); 
    tok.parseNumbers(); 

    tok.nextToken(); 

    int  rows = (int) tok.nval; 
    int[][] out = new int[rows][]; 

    for(int i = 0; i < rows; i++) { 
     tok.nextToken(); 

     int length = (int) tok.nval; 
     int[] row = new int[length]; 
     out[i]  = row; 

     for(int j = 0; j < length; j++) { 
      tok.nextToken(); 
      row[j] = (int) tok.nval; 
     } 
    } 

    return out; 
} 
+0

你是最棒的,男人。你的代碼完美地工作。 – Ring 2012-02-13 06:56:55