我如何使用scanner(java)处理它?

时间:2010-01-17 08:20:54

标签: java java.util.scanner

我有关于扫描仪的问题;我在一家小公司工作;我们有一个软件;它会生成一个大文本文件;我们必须从中获得一些有用的信息;我想用java编写一个简单的应用程序来节省时间;你能指导我吗?

例如我想要这个输出;

输出


RFID:25 BLUID:562 WifiID:2610 RFID:33

RFID数量:2

,例如;这是我的文本文件,因为每个使用我们软件生成的文件都有14000行:)

--------------------------
AAAAAAAAAAAA;RFID=25;
BBBB;BBBBBBBB;BBBBBBBBBB;
CCCCC;fffdsfdsfdfsd;BLUID=562;dfsdfsf;
fgfdgdf;terter;fdgfdgtryt;
trtretrre;WifiID=2610;trterytuytutyu;
zxzxzxzxz;popopopwwepp;RFID:33;aasasds…
gfdgfgfd;gfdgfdgfd;fdgfgfgfd;

我用这个源代码测试它但我无法处理它;

Scanner scanner = new Scanner("i:\1.txt");

scanner.findInLine("RFID=");

if (scanner.hasNext())
System.out.println(scanner.next());
else
System.out.println("Error!");

请帮助我;

非常感谢...

5 个答案:

答案 0 :(得分:7)

以下是使用StreamTokenizer的示例:

import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Scanner;

public class ScannerTest {

    private static final String s = ""
        + "AAAAAAAAAAAA;RFID=25;\n"
        + "BBBB;BBBBBBBB;BBBBBBBBBB;\n"
        + "CCCCC;fffdsfdsfdfsd;BLUID=562;dfsdfsf;\n"
        + "fgfdgdf;terter;fdgfdgtryt;\n"
        + "trtretrre;WifiID=2610;trterytuytutyu;\n"
        + "zxzxzxzxz;popopopwwepp;RFID:33;aasasds…\n"
        + "gfdgfgfd;gfdgfdgfd;fdgfgfgfd;\n";

    public static void main(String[] args) {
        long start = System.nanoTime();
        tokenize(s);
        System.out.println(System.nanoTime() - start);
        start = System.nanoTime();
        scan(s);
        System.out.println(System.nanoTime() - start);
    }

    private static void tokenize(String s) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        StreamTokenizer tokens = new StreamTokenizer(new StringReader(s));
        tokens.whitespaceChars(';', ';');
        try {
            int token;
            String id;
            do {
                id = tokens.sval;
                token = tokens.nextToken();
                if (token == '=' || token == ':') {
                    token = tokens.nextToken();
                    Integer count = map.get(id);
                    map.put(id, count == null ? 1 : count + 1);
                    System.out.println(id + ":" + (int) tokens.nval);
                }
            } while (token != StreamTokenizer.TT_EOF);
            System.out.println("Counts:" + map);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void scan(String s) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        Scanner scanner = new Scanner(s).useDelimiter(";");
        while (scanner.hasNext()) {
            String token = scanner.next();
            String[] split = token.split(":");
            if (split.length == 2) {
                Integer count = map.get(split[0]);
                map.put(split[0], count == null ? 1 : count + 1);
                System.out.println(split[0] + ":" + split[1]);
            } else {
                split = token.split("=");
                if (split.length == 2) {
                    Integer count = map.get(split[0]);
                    map.put(split[0], count == null ? 1 : count + 1);
                    System.out.println(split[0] + ":" + split[1]);
                }
            }
        }
        scanner.close();
        System.out.println("Counts:" + map);
    }
}
RFID:25
BLUID:562
WifiID:2610
RFID:33
Counts:{RFID=2, BLUID=1, WifiID=1}
1103000
RFID:25
BLUID:562
WifiID:2610
RFID:33
Counts:{RFID=2, BLUID=1, WifiID=1}
22772000

答案 1 :(得分:3)

你的建议来源不会做你想要的。扫描仪使用分隔符分解输入。默认分隔符是空格(空格,制表符或换行符)。 Scanner.hasNext()只是告诉您是否有新的空格分隔标记。 Scanner.next()只返回该标记。请注意,这些都不受Scanner.findInLine(模式)影响,因为它只是在当前行搜索提供的模式。

也许是这样的(我没有测试过这个):

Scanner scanner = new Scanner("i:\\1.txt");
scanner.useDelimiter(";");
Pattern words = Pattern.compile("(RFID=|BLUID=|WifiID=)");//just separate patterns with |
while (scanner.hasNextLine()) {
  key = scanner.findInLine(words);
  while (key != null) {
    String value = scanner.next();
    if (key.equals("RFID=") {
      System.out.print("RFID:" + value);
    } //continue with else ifs for other keys
    key = scanner.findInLine(words);
  }
  scanner.nextLine();
}

我建议你忘记使用扫描仪,只使用BufferedReader和一些Pattern对象,因为这种方法对你想做的事情更灵活。

答案 2 :(得分:2)

准备好运行:

public class ScannerTest {

    private static void readFile(String fileName) {

        try {
            HashMap<String, Integer> map = new HashMap<String, Integer>();
            File file = new File(fileName);

            Scanner scanner = new Scanner(file).useDelimiter(";");
            while (scanner.hasNext()) {
                String token = scanner.next();
                String[] split = token.split(":");
                if (split.length == 2) {
                    Integer count = map.get(split[0]);
                    map.put(split[0], count == null ? 1 : count + 1);
                    System.out.println(split[0] + ":" + split[1]);
                } else {
                    split = token.split("=");
                    if (split.length == 2) {
                        Integer count = map.get(split[0]);
                        map.put(split[0], count == null ? 1 : count + 1);
                        System.out.println(split[0] + ":" + split[1]);
                    }
                }
            }
            scanner.close();
            System.out.println("Counts:" + map);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        readFile("test.txt");
    }
}

答案 3 :(得分:1)

你的第一行存在问题。

  1. 您需要在字符串文字内转义反斜杠("i:\\1.txt"而非"i:\1.txt"
  2. 用于从文件读取的Scanner构造函数采用File参数(或InputStream参数)。采用String参数的构造函数是从该实际字符串中读取的。请参阅javadoc
  3. 尝试

    Scanner scanner = new Scanner(new File("i:\\1.txt"));
    

答案 4 :(得分:0)

一些起始代码:

String filename = "your_text_file";
Scanner sc = new Scanner(filename);

// use the scanner to iterate through every line in the file:
try{
while(sc.hasNextLine()){
    String line = sc.nextLine();
    // split the line up into space-separated tokens:
    String[] tokens = line.split();
    // look through the tokens to find what you are looking for:
    for(int i = 0; i<tokens.length; i++){
        if(tokens[i].equals("search_word){
             // Do stuff
        }
    }
}
} // end try
catch(Exception e){}