使用扫描仪将txt文件读入数组
我有一个文本文件,大致如下所示:
类型、距离、长度、其他
A、62、17、abc、
A、12、4、、
A、6、90、、
A、46、53、、
等。
所有内容均以逗号分隔,但有时会有空白的。我需要能够使用扫描仪(而不是缓冲读取器)将这些数据读入数组,并能够以某种方式解释空白,以及用逗号分隔。稍后我将需要能够使用每列中的数据进行计算。如何将这些数据放入数组中?
这是我到目前为止所拥有的:(java)
import java.util.Scanner;
import java.io.*;
public class RunnerAnalysis {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.print("File: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
inputFile.nextLine();
String line = inputFile.nextLine();
while(inputFile.hasNext())
{
String[] array = line.split(",");
}
}
}
I have a text file that looks roughly like this:
type, distance, length, other,
A, 62, 17, abc,
A, 12, 4,,
A, 6, 90,,
A, 46, 53,,
etc.
Everything is separated by commas, but sometimes there is a blank. I need to be able to read this data into an array using a scanner (not bufferedreader) and be able to account for the blanks somehow, as well as split by commas. Later I will need to be able to calculate things with the data in each column. How do I get this data into the array?
This is what I have so far: (java)
import java.util.Scanner;
import java.io.*;
public class RunnerAnalysis {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.print("File: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
inputFile.nextLine();
String line = inputFile.nextLine();
while(inputFile.hasNext())
{
String[] array = line.split(",");
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您确实想使用扫描仪(恕我直言,这不是一个好主意),您可以将分隔符设置为
,
。我更喜欢将
BufferedReader
与String.split(",")
结合使用。If you really want to use a Scanner, which is IMHO not such a good idea, you can set the delimiter to
,
.I prefer using a
BufferedReader
in combination withString.split(",")
.