将格式化文本文件读入数组列表JAVA
我需要我的java程序来读取格式化的文本文件,我将给出一个如何格式化的示例 所以#1是列出的国家数量,A是区域,新西兰是国家 所以我知道我需要读取#之后的数字,这就是运行循环的次数,然后下一行包含区域名称,它将是数组列表的名称。但说到真正做到这一点,我真是迷路了 目前我的代码是这样的将格式化文本文件读入数组列表JAVA,java,arrays,arraylist,stream,Java,Arrays,Arraylist,Stream,我需要我的java程序来读取格式化的文本文件,我将给出一个如何格式化的示例 所以#1是列出的国家数量,A是区域,新西兰是国家 所以我知道我需要读取#之后的数字,这就是运行循环的次数,然后下一行包含区域名称,它将是数组列表的名称。但说到真正做到这一点,我真是迷路了 目前我的代码是这样的 import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Ar
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;
}
}
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.io.PrintWriter;
导入java.util.ArrayList;
导入java.util.Scanner;
公务舱目的地{
弦带;
阿拉伯国家;
公共对象目标列表(){
扫描器s=null;
试一试{
s=新扫描仪(新文件(“Files/Destination.txt”);
}catch(filenotfounde异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
ArrayList destinations=新的ArrayList();
而(s.hasNext()){
destinations.add(s.nextLine());
}
s、 close();
int sz=destinations.size();
对于(int i=0;i
但这只是将文本文件转储到一个数组列表中您不需要额外的带有区域和国家的类,它可以完美地与Map一起工作:
private Map<String, List<String>> destinations = new HashMap<>();
private Map destinations=new HashMap();
要使用文件中的值填充映射,可以编写类似(未测试)的内容
Scanner s=新扫描仪(新文件(“Files/Destination.txt”);
int currentCount=0;
字符串currentZone=“”;
而(s.hasNextLine()){
字符串行=s.nextLine();
如果(第行开始使用(“#”)号{//国家数
currentCount=Integer.parseInt(第行子字符串(1));
}如果(line.length()=1){//zone
currentZone=线路;
destinations.put(currentZone,新数组列表(currentCount));
}else{//将国家/地区添加到当前区域
destinations.get(currentZone).add(line);
}
}
在问题中至少张贴几行文本文件,并添加预期结果。
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);
}
}