使用扫描仪读入文本文件

时间:2016-04-14 00:39:02

标签: java

我有一个文本文件,其中包含以下行定义:Hi 0x01.我正在尝试阅读单词Hi并将其存储在自己的变量中,并将0x01存储在自己的变量中我遇到的问题是我似乎能够在Hi中阅读,但我可以t read in 0x01`。这是我的代码

File comms =new File("src/Resources/com.txt");
        try (Scanner scan = new Scanner(comms)) {
            while (scan.hasNext()) {
                String line = scan.nextLine();
                Scanner sc = new Scanner(line);
                sc.useDelimiter("\\s+");
                try {
                  String comm1 = sc.next();
                 // System.out.println(comm1);
                 int value =sc.nextInt();
                 System.out.println(value);
                 sc.close();
                } catch (Exception ef){

                }

1 个答案:

答案 0 :(得分:2)

老实说,我不知道你在这里做了什么。您最好扫描一次:

    File comms = new File("src/Resources/com.txt");
    try(Scanner scan = new Scanner(comms)) {
        while(scan.hasNext()) {
            String line = scan.nextLine();

            String[] words = line.split(" ");

            System.out.println(words[0]); // "Hi"
            System.out.println(words[1]); // "0x01"
        }
    }
    catch(Exception e) {

    }

现在,将它们放在单独的字符串中,您可以在世界上做任何事情,例如将单词[1]转换为int。

相关问题