【发布时间】:2020-04-12 06:01:53
【问题描述】:
我想知道如何读取带有斜线的文本文件并将它们放入数组中?我似乎无法弄清楚如何拆分它们。
TXT 文件内容:
ID Name Price Stock
00011 / Call of Duty: Modern Warfare / 2499 / 10
00012 / The Witcher 3: Wild Hunt / 1699 / 15
00013 / Doom Eternal / 2799 / 20
00014 / Outlast 2 / 1999 / 11
00015 / Forza Horizon 4 / 2799 / 5
这是我获取 ID 的示例代码:
File file1 = new File("stock\\consoles\\consoles.txt");
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(String.valueOf(file1)));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.next();
s1.nextLine();
}
String[] ID = new String[ctr];
Scanner s2 = new Scanner(new File(String.valueOf(file1)));
for (int i = 0; i < ctr; i++) {
ID[i] = s2.next();
s2.nextLine();
System.out.println(Arrays.toString(ID));
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
当我运行代码时,我得到了这个:
[00011, null, null, null, null]
[00011, 00012, null, null, null]
[00011, 00012, 00013, null, null]
[00011, 00012, 00013, 00014, null]
[00011, 00012, 00013, 00014, 00015]
预期的输出是:
00011
00012
00013
00014
00015
我想把它放入 ID、Name、Price 和 Stock 的数组中,格式如下:
String[] ID = new String[ctr];
String[] NAME = new String[ctr];
String[] PRICE = new String[ctr];
String[] STOCK = new String[ctr];
任何帮助将不胜感激!谢谢。
【问题讨论】:
-
因格式问题已编辑。
标签: java file java.util.scanner filereader