2014-01-21 94 views
0

我已將網格轉換爲CSV格式,將其轉換爲字符串以保存網格。將CSV字符串[]轉換爲字符串[] []

但是,當我想要打開CSV文件時,我必須將字符串變成2D數組..我試圖弄清楚如何去做,但我不確定如何加入兩個string[]以便它變成一個二維數組。

我添加了一個;行結束並且必須開始一個新行,但我對如何將它添加在一起感到困惑。

代碼:

public static void open() { 
      // The name of the file to open. 
      String name = JOptionPane.showInputDialog(null, 
        "Enter the name of the file you wish to open: "); 
      String fileName = name+ ".txt"; 

      // This will reference one line at a time 
      String line = null; 

      char gridWorld[][]; 

      try { 
       // FileReader reads text files in the default encoding. 
       FileReader fileReader = new FileReader(fileName); 

       // Always wrap FileReader in BufferedReader. 
       BufferedReader bufferedReader = new BufferedReader(fileReader); 

       String[] firstsplit, secondsplit; 
       while ((line = bufferedReader.readLine()) != null) { 
        for(int i = 0; i < line.length(); i++){ 
         firstsplit = line.split(";"); // if semi colon, replace with new line 

        } 

        secondsplit = line.split(","); // splitting the line in columns 

       } 

       // Always close files. 
       bufferedReader.close(); 

任何幫助,將不勝感激。

回答

3

.csv文件格式與行#和指標:

 | columnIndex 
     | 1 2 3 4 
---------------- 
line1 | 1,2,3,4 
line2 | 5,6,7,8 
line3 | 9,a,b,c 
... 
lineN | w,x,y,z 

有了這個可視化的就應該很容易看到如何解析它。下面的代碼片段閱讀到你gridWorld陣列,希望這有助於:

lineIndex = 0; 
while ((line = br.readLine()) != null) { 
    String[] split = line.split(","); 
    for (int i=0; i<split.length; i++) { 
     gridWorld[lineIndex][i] = split[i].charAt(0);   
    } 
    lineIndex++; 
} 
+0

我得到的錯誤..'類型不匹配:無法從字符串轉換爲字符'在分裂[i]位.. – user3209940

+0

我修改了代碼,通過添加'.chartAt(0)'。 – kmera

+0

這將需要你知道你的網格的大小,當初始化'gridWorld' –

0

如果您輸入csv文件是在形狀錯誤

words,things,stuff;more words, more stuff, more things 
line2 words,line2 stuff,line2 things; 

因此,有多個行與;文件中在你想分離成不同行的行中,這樣你的輸出就是

words,things,stuff 
more words,more stuff, more things 
line2 words,line2 stuff,line2 things 

你需要做的是讀每行首先a nd把它分成;這些在內存中。下面的方法也意味着你不需要知道網格的大小提前

ArrayList<String> al = new ArrayList<String>(); 
while ((line = br.readLine()) != null) { 
{ 
    String[] split1 = line.split(";"); 
    for(String s1 : split1) 
     al.add(s1); 
} 

String[][] gridWorld = new String[al.size()][]; 

for(int i = 0; i < al.size(); i++) 
{ 
    gridWorld[i] = al.get(i).split(","); 
} 

而這都可以降低到這個

ArrayList<String> al = new ArrayList<String>(); 
while ((line = br.readLine()) != null) { 
    al.addAll(Arrays.asList(line.split(";"))); 

String[][] gridWorld = new String[al.size()][]; 

for(int i = 0; i < al.size(); i++) 
    gridWorld[i] = al.get(i).split(",");