2017-08-01 49 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(); 
    }