我有一个关于扫描仪的问题:我在一家小公司工作;我们有一个软件;它生成一个大文本文件;我们必须从它得到一些有用的信息;我想用java编写一个简单的应用程序,以节省时间;请您指导我好吗?
例如,我想要这个输出;
输出
射频识别: 25蓝光: 562 WifiID : 2610射频识别: 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!");请帮帮我;
非常感谢..。
发布于 2010-01-17 09:08:11
你建议的线人不会做你想做的事。扫描器使用分隔符拆分输入。默认的分隔符是空格(空格、制表符或换行符)。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和几个模式对象,因为该方法对于您想要做的事情更加灵活。
发布于 2010-01-17 09:12:15
准备运行:
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");
}
}发布于 2010-01-17 08:51:07
你的第一行有问题。
"i:\\1.txt"而不是"i:\1.txt")Scanner构造函数采用File参数(或InputStream参数)。接受String参数的构造函数是从实际字符串中读取的。见javadoc。试一试
Scanner scanner = new Scanner(new File("i:\\1.txt"));https://stackoverflow.com/questions/2080403
复制相似问题