简体   繁体   中英

Using Scanner to read in a text file

I have a text file with the following line define : Hi 0x01. I'm trying to read in the word Hi and store it in its own variables and 0x01 in its own variable.The problem I'm having is that i seem to be able to read in Hi , but i can t read in 0x01`.Here is my code

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){

                }

I honestly have no idea what you're trying to do here. You'd better scan it once:

    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) {

    }

Now, having these in separate strings you can do anything in the world with it like converting words[1] to int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM