[英]Java File Scanning multiple lines and variable types
尝试扫描具有许多行,多种类型的变量和多个段的文件(也许不是描述它的最佳词吗?)
基本上这是我的文件输入(占位符可以更好地解释):
String1
int1
double1
String2
int2
double2
String3
int3
double3
我想知道获取此数据以便在基本方程式中使用的最佳方法是什么。
我已经研究过使用Scanner了,但是由于有多行,所以我似乎最好使用BufferedReader,然后将每行从一个字符串转换为一个整数或一个双精度(如果需要的话)(或者我是否使这个复杂化了?)。
我以前有一些C ++的经验,但是除了循环和数组的基础知识外,别无其他,因此请尽量保持清晰和初学者的证明。
由于您的文件为string,int,double,空白行,string,int,double,...我们可以轻松地为此使用while循环。 制作3个包含相应字符串,整数和双精度的Arraylist。
public static void main(String[] args){
Scanner file = new Scanner(new File("file path here"));
ArrayList<String> strings = new ArrayList<String>();
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<Double> doubles = new ArrayList<Double>();
while(file.hasNextLine()){
strings.add(file.nextLine());
ints.add(Integer.parseInt(file.nextLine()));
doubles.add(Double.parseDouble(file.nextLine()));
if(file.hasNextLine())
file.nextLine();
}
file.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.