【发布时间】:2019-10-12 23:24:52
【问题描述】:
目前正在开发一个程序,该程序读取足球运动员的统计数据并将数据转换为二进制并将其全部写入文件。我遇到的问题是解析我正在读取的文件包含的所有不同数据类型。我正在阅读的文件将具有以下格式 - lastName yearsExp position height weight 40ydSpeed team active?文件如下所示:Brady, 14, QB, 1, 210, 4.9, Patriots, true 我想知道如何解析不同的数据类型,int、char、double、String 和 boolean。
到目前为止,我的程序要求用户输入一个文件,它会从无效文件中捕获任何 FileNotFoundExceptions 并循环,直到输入一个有效文件。然后程序读取文件并将其全部存储到列表中。
public static void main(String[] args) throws IOException {
File file;
Scanner inputFile;
Scanner readFile;
String line;
String fileName;
int x = 1;
ArrayList<String> stats = new ArrayList<String>();
do {
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the name of a " +
"file containing football player data:");
fileName = kb.nextLine();
try {
file = new File(fileName);
inputFile = new Scanner(file);
while(inputFile.hasNext()) {
stats.add(inputFile.nextLine());
}
x=2;
}
catch (FileNotFoundException e)
{
System.out.print("File not found. ");
}
}
while(x==1);
for (String s : stats) {
System.out.println(s);
}
// TODO use the following methods for writing to binary
// TODO writeUTF, writeInt, writeChar, writeInt, writeInt, writeDbl, writeByte
【问题讨论】:
-
看起来值是用逗号分隔的,所以我建议你使用 CSV 解析器(CSV = Comma-Separated-Values)。
-
在我看来,您应该创建一个 Player 类并使用它。无论如何,您以后很可能需要它来处理数据。
标签: java exception file-io binary