2017-08-01 60 views
0

我正在嘗試讀取.txt文件,並且我想解析/標記每行以便我可以加載到結構。最後,結構將被添加/推送到struct類型的向量。但是,addEllement()功能不起作用!任何知道如何將結構添加到vector的人?java矢量用法

樣品的編號:

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.concurrent.TimeUnit; 
import java.util.*; 

/* 
* STRUCT TO STORE PARSED DATA 
*/ 
class my_struct 
{ 
    String name; 
    String id; 
    String comment; 
} 
public class read 
{ 
    //Vector of type my_struct to store data 
public static Vector<my_struct> plugin_group_list=new Vector<my_struct>(); 
    try 
     { 
      //opening my file 
      File file = new File("file.txt"); 
      FileReader fileReader = new FileReader(file); 
      BufferedReader bufferedReader = new BufferedReader(fileReader); 
      my_struct[] list_plugin_param=new my_struct[100]; 
      String line; 
      while ((line = bufferedReader.readLine()) != null) 
      { 
       String[] result = line.split("~"); 
       for (int x=0; x<result.length; x++) 
       { 
        list_plugin_param[x] = new my_plugin(); 
        if(x==0) 
        { 
         list_plugin_param[x].name=result[x]; 
        }    
        if(x==1) 
        { 
         list_plugin_param[x].id=result[x]; 
        } 
        if(x==2) 
        { 
         list_plugin_param[x].comment=result[x]; 
        } 
       } 
plugin_group_list.addEllement(list_plugin_param);//this doesn't work for me 
      } 
      fileReader.close(); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
} 

file.txt的看起來像下面

John~0001~this is John 
smith~0002~this is smith 
.. 
.. 
.. 
+1

爲什麼你需要載體,是的ArrayList <>還不夠嗎? – Steephen

+2

嘗試修復代碼:'addEllement - > addElement' – Vincent

+0

您正在考慮的太多了,因爲C++,java沒有結構,只是使用ArrayList –

回答

0

這是溶液)

plugin_group_list.addAll(Arrays.asList(list_plugin_param ));

0

如果您有必要區分名稱,ID和註釋字段,請嘗試將其設置爲地圖,然後將其添加到列表中。

列表中的每一行應該代表文件中新行的名稱,標識和註釋。

這裏是什麼你可能嘗試大綱:

try 
    { 
     ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>(); 
     //opening my file 
     File file = new File("file.txt"); 
     FileReader fileReader = new FileReader(file); 
     BufferedReader bufferedReader = new BufferedReader(fileReader); 

     String line; 
     while ((line = bufferedReader.readLine()) != null) 
     { 
      HashMap<String,String> newLine = new HashMap<String,String>(); 
      String[] result = line.split("~"); 
      for (int x=0; x<result.length; x++) 
      { 
       if(x==0) 
       { 
        newLine.put("name",result[x]); 
       }    
       if(x==1) 
       { 
        newLine.put("id",result[x]); 
       } 
       if(x==2) 
       { 
        newLine.put("comment",result[x]); 
       } 
      } 
      list.add(newLine); 
     } 
     fileReader.close(); 
    }