簡體   English   中英

使用掃描儀讀取文本文件

[英]Using Scanner to read in a text file

我有一個帶有以下行定義的文本文件: Hi 0x01. 我正在嘗試讀取Hi並將其存儲在其自己的變量中,並將0x01存儲在其自己的變量中。我遇到的問題是我似乎能夠在Hi讀取,但我無法t read in 0x01中t read in `這是我的代碼

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

                }

老實說,我不知道您要在這里做什么。 您最好掃描一次:

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

    }

現在,將它們放在單獨的字符串中,您可以執行任何操作,例如將words [1]轉換為int。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM