所以我有一个包含这样列表的文件
2134:193
192:1856
1092:1850
980:759
等等
我想处理该文件并将其添加到数组中,然后能够获取 int 的
就像我想做的那样 System.out.println("第一+": "+第二);
不确定存储它的最佳方式是什么,但这是我迄今为止的尝试
public static void loadList() {
BufferedReader br = new BufferedReader(new FileReader("./data.txt"));
String line;
while ((line = br.readLine()) != null) {
String args[];
args = line.split(":");
int first = Integer.toInt(args[0]);
int second = Integer.toInt(args[1]);
System.out.println(first + " : " + second);
}
br.close();
}
最佳答案
试试这个:
Class
Class DataClass
{
public int first; // Deliberately public
public int second;
public DataClass(int val1, int val2){
this.first = val1;
this.second = val2;
}
}
Code
public static void loadList() {
ArrayList<DataClass> pairList = new ArrayList<DataClass>();
BufferedReader br = new BufferedReader(new FileReader("./data.txt"));
String line;
while ((line = br.readLine()) != null) {
String args[] = line.split(":");
int first = Integer.valueOf(args[0]);
int second = Integer.valueOf(args[1]);
DataClass valPair = new DataClass(first,second);
pairList.add(valPair);
System.out.println(valPair.first + " : " + valPair.second);
}
br.close();
}
确保您有正确的 try catch 语句
关于java - 将文本文件转为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19328818/