【发布时间】:2020-05-14 07:02:03
【问题描述】:
如何获取 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 等等?
文本文件内容:
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++;,但没有输出任何内容。任何帮助将不胜感激,谢谢!
【问题讨论】:
-
你可以使用正则表达式
-
@Erwin 你好,需要什么样的正则表达式?
-
获取 id,将其与正则表达式匹配,如果匹配,即包含 id 00012 或更大或直到 00099,则使用它
-
或者你只能查看id?如果它比 12 大,那就拿去吧?
-
取最后2位然后比较
标签: java arrays string java.util.scanner indexof