2014-09-30 60 views
0

我需要我的Java程序来读取一个格式化的文本文件,我就给它是如何格式化阅读格式的文本文件转换成数组列表JAVA

http://i.stack.imgur.com/qB383.png

为例所以#1的数列出的国家,A是该区域,而新西兰是该国家。

所以我知道我需要在#之后读取数字,并且这是多少次运行循环,然后下一行包含区域名称,这将是数组列表的名称。但为了实现这个目标,我超级迷失了。

目前我的代码看起来像这样,

import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.util.ArrayList; 
import java.util.Scanner; 


public class destination{ 

    String zone; 
    ArrayList<String> countries; 

    public Object destinationList(){ 

     Scanner s = null; 
     try { 
      s = new Scanner(new File("Files/Destination.txt")); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     ArrayList<String> destinations = new ArrayList<String>(); 
     while (s.hasNext()) { 
      destinations.add(s.nextLine()); 

     } 
     s.close(); 

     int sz = destinations.size(); 

     for (int i = 0; i < sz; i++) { 
      System.out.println(destinations.get(i).toString()); 
     } 

     return destinations; 
    } 

} 

但这只是转储文本文件到一个数组列表

+0

在问题中至少发布几行文本文件,并添加预期结果。 – Mena 2014-09-30 09:31:44

回答

0

你并不需要具有区域和国家的额外的类,它将工作与完善地图:

private Map<String, List<String>> destinations = new HashMap<>(); 

要使用文件中的值填充地图,可以编写类似(未测试)的内容。

Scanner s = new Scanner(new File("Files/Destination.txt")); 
int currentCount = 0; 
String currentZone = ""; 
while(s.hasNextLine()) { 
    String line = s.nextLine(); 
    if (line.startsWith("#") { // number of countries 
     currentCount = Integer.parseInt(line.substring(1)); 
    } else if (line.length() == 1) { // zone 
     currentZone = line; 
     destinations.put(currentZone, new ArrayList<String>(currentCount); 
    } else { // add country to current zone 
     destinations.get(currentZone).add(line); 
    } 
}