如何获取txt文件的某些部分并将其放入数组或字符串中?
我已经有一个读取txt文件中25个项目的代码。
try {
File file = new File("filepath");
Scanner sc = new Scanner(file);
String[] ids = new String[25];
String[] names = new String[25];//---- set your array length
String[] prices = new String[25];
String[] stocks = new String[25];
int counter = 0;
while (sc.hasNext()) {
String data = sc.nextLine();
if (data.contains("/")) {
String[] elements = data.split("/");
ids[counter] = elements[0].trim();
names[counter] = elements[1].trim();
prices[counter] = elements[2].trim();
stocks[counter] = elements[3].trim();
// other elements[x] can be saved in other arrays
counter++;
}
}
image.setIcon(graphicsconsole[productTable.getSelectedRow()]);
iteminfo.setText("" + names[productTable.getSelectedRow()]);
itemdescription.setText("Price: P " + prices[productTable.getSelectedRow()]);
itemstock.setText("Stocks: " + stocks[productTable.getSelectedRow()]);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (ArrayIndexOutOfBoundsException exx) {
}
如您所见,它现在被排列成数组,我将它们用作JTable
的选择列表。
如果我打印ids[counter] = elements[0].trim();
,它将是:
00011
00012
00013
00014
00015
and so on...
问题是,如果要获取txt文件的特定部分该怎么办?例如,我希望它不读取ID号00011
,而是希望读取ID 00012
,依此类推?
Txt文件内容:
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 00011
之后的ID,则预期的输出将是:
00012
00013
00014
00015
我尝试编辑int counter = 0
和counter++;
,但没有输出任何内容。任何帮助将不胜感激,谢谢!
您可以对内部循环执行以下操作:
String token = "00011";
Boolean hit = false;
while (sc.hasNext()) {
String data = sc.nextLine();
if (data.contains("/") && hit) {
String[] elements = data.split("/");
ids[counter] = elements[0].trim();
names[counter] = elements[1].trim();
prices[counter] = elements[2].trim();
stocks[counter] = elements[3].trim();
// other elements[x] can be saved in other arrays
counter++;
}
if (!hit && data.contains(token)) {
hit = true;
}
}
以这种方式检查您的字符串是否包含要在其后启动的令牌,并且仅在令牌出现在上一行之后才开始处理这些行。