【问题标题】:How to read txt file with slashes “/” with scanner input and reads certain parts?如何使用扫描仪输入读取带有斜杠“/”的 txt 文件并读取某些部分?
【发布时间】: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 = 0counter++;,但没有输出任何内容。任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 你可以使用正则表达式
  • @Erwin 你好,需要什么样的正则表达式?
  • 获取 id,将其与正则表达式匹配,如果匹配,即包含 id 00012 或更大或直到 00099,则使用它
  • 或者你只能查看id?如果它比 12 大,那就拿去吧?
  • 取最后2位然后比较

标签: java arrays string java.util.scanner indexof


【解决方案1】:

请注意,以下解决方案会读取内存中的所有文件内容,请勿尝试将其用于非常大的文件。

File f = new File("filepath");
// read all lines
List<String> lines = Files.readAllLines(f.toPath());
lines.stream()
    // skip lines before 00013 (change here to your needs)
    .dropWhile(l -> !l.startsWith("00013"))
    // ensure the lines have '/' character
    .filter(l -> l.contains("/"))
    .forEach(data -> {
        // do something with each line, starting the one with 00013
        String[] elements = data.split("/");
        String id = elements[0].trim();
        System.out.println(id);
    });
// if you just want the IDs ...
lines.stream()
    .dropWhile(l -> !l.startsWith("00013"))
    .filter(l -> l.contains("/"))
    // get the ID for each line
    .map(l -> l.split("/")[0].trim())
    // print it
    .forEach(System.out::println);
// if you want the IDs to a List instead of printing ...
final List<String> ids = lines.stream()
    .dropWhile(l -> !l.startsWith("00013"))
    .filter(l -> l.contains("/"))
    .map(l -> l.split("/")[0].trim())
    .collect(Collectors.toList());

只是为了说明dropWhile部分:

输入:

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

代码:

lines.stream()
    .dropWhile(l -> !l.startsWith("00013"))
    .forEach(System.out::println);

输出:

00013   / Doom Eternal                    / 2799       / 20
00014   / Outlast 2                       / 1999       / 11
00015   / Forza Horizon 4                 / 2799       / 5

【讨论】:

  • 请问如何将这些数组制作成索引?供iteminfo.setText("" + names[productTable.getSelectedRow()]);使用
  • 不确定你的意思。您想根据游戏的 ID 或名称获取股票吗?
  • 用于JTable中的选择。它加载txt文件,获取id,项目名称等。然后当用户在JTable中选择一行时,它将设置JLabels。
  • 但是 JTable 已经填充了,因为您可以选择一行,不是吗?目前尚不清楚您要达到的目标。
  • 哦,所以当您选择一行时,您希望更新一些 JLabel 吗?
猜你喜欢
  • 1970-01-01
  • 2012-11-02
  • 2013-12-04
  • 1970-01-01
  • 2022-01-07
相关资源
最近更新 更多