如何在扫描仪输入中读取带有斜线“ /”的txt文件并将其放入数组/字符串中

问题描述 投票:1回答:1

我想知道如何读取带有斜杠的文本文件并将其放入数组?我似乎无法弄清楚如何拆分它们。

TXT FILE内容:

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,名称,价格和库存的数组中:

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
1个回答
3
投票

尝试此

        File file = new File("C:\\Users\\***\\Desktop\\name.txt"); 
        Scanner sc = new Scanner(file);
        String[] ids=new String[5]; //---- set your array length
        int counter=0;
        while(sc.hasNext()) {           
            String data=sc.nextLine();
            if(data.contains("/")) { // ignores your data header
                String[] elements=data.split("/");
                ids[counter]=elements[0].trim();
                  // other elements[x] can be saved in other arrays
                counter++;
            }       
}
    for(String i:ids) {
        System.out.println(i);
    }

这将为您提供输出:

00011
00012
00013
00014
00015

© www.soinside.com 2019 - 2024. All rights reserved.