2013-06-25 81 views
1

我有沉重的.txt文件。它包含一个格式像这样:从.txt文件中读取并转换为列表<Map>

0  1 2 3 4 5 6 7 ... n 
0 A,  B, c, D, E, F, G, H, 
1 AA, BB, CC, DD, EE, FF, GG, HH, 
2 
3 
. 
. 
n 

我想保存在Map中的每一行。例如在第一行中: :地图< 0,A>。地图< 1,B>,地图< 2,C>,... 然后我想将这张地图保存在列表中。例如我想要在列表中保存100行。例如,如果我写这个函数:“”list.get(1).get(4); “”我收到“EE” 这意味着首先我必须进入1排,然后我去4并收回“EE”。 可否请指导我如何解决这个问题? 我看了一些关于“春天批”的文章。它与我想要的 有什么关系吗?请问我该如何解决这个问题?

public class spliter { 
    static int w=0; 
    private static HashMap<Integer,String> map = new HashMap<Integer,String>(); 
    private static List<Map<Integer, String>> list=new ArrayList<Map<Integer,String>>(); 
    public static void main(String[] args) throws IOException{ 
     String string = null; 
     try { 
      BufferedReader reader = new BufferedReader(new FileReader("C:\\test.txt")); 

      while((string = reader.readLine()) != null) { 

       String[] parts = string.split(","); 
       int i=parts.length; 
       for(int j=0; j<i; j++){ 
        map.put(j, parts[j]); 
       }   
       list.add(map); 
       w++; 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

哪里是你的代码? –

+3

我不认为你应该担心Spring Batch。这是一个编程问题 - 将Spring Batch加入混合只会使事情复杂化。到目前为止你写了什么? – DaveH

回答

3

这样简单的事情可以用扫描仪读取每一行然后用String.split(...)来分割每一行。例如:

while line exists 
    read line into String using Scanner 
    split String using String#split(...) 
    use array from split to create a list 
    add above list to master list 
end while 

请注意,您可以在清单列表中包含此内容,而不需要Map,完全可以。 List<List<String>>应该为你做。

我认为,对您来说,我们给您这样的一般性建议,然后看看您可以用它做些什么,对您更具启发性。

我已经成为一个社区Wiki,所以所有人都可以轻松地为这个答案做出贡献,所以没有人会获得最高票数的声望。

+1

+1我想知道如何回答这个问题。 – zEro

+0

它是有用的! – Ritz

+0

@ M.rEzAmOjaLlaL:很高兴帮助。 –

-1

你能我们像这样

public class ArrayReader { 
public static void main(String[] args) { 
    List<List<String >> array = new ArrayList<>(); 
    try (BufferedReader br = new BufferedReader(new FileReader("file.txt"));){ 
    String line; 
    while ((line=br.readLine())!=null) 
     array.add(Arrays.asList(line.split(","))); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

}