Come posso gestire la cosa con scanner (Java)?
-
21-09-2019 - |
Domanda
Ho una domanda su Scanner, io lavoro in una piccola azienda; abbiamo un software; si genera un file di testo grande; e dobbiamo ottenere alcune informazioni utili da esso; Voglio scrivere una semplice applicazione con java per risparmio di tempo; potrebbe per favore mi guida?
per esempio voglio questa uscita;
Output
RFID: 25 BLUID: 562 WifiID: 2610 RFID: 33
RFID Count: 2
e, per esempio, questo è il mio file di testo, perché ogni file generato con il nostro software, dispone di 14000 linee:)
--------------------------
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;
I test con il codice sorgente, ma non riesco a gestirlo;
Scanner scanner = new Scanner("i:\1.txt");
scanner.findInLine("RFID=");
if (scanner.hasNext())
System.out.println(scanner.next());
else
System.out.println("Error!");
ti prego, aiutami;
Grazie mille ...
Soluzione
Bene la vostra fonte suggerito non fare quello che vuoi. Scanner rompe ingresso utilizzando un delimitatore. Il delimitatore di default è di spaziatura (spazi, tabulazioni o ritorni a capo). Scanner.hasNext () ti dice semplicemente se c'è un nuovo spazio bianco delimted token. Scanner.next () restituisce semplicemente che token. Si noti che nessuna di queste vengono effettuate da Scanner.findInLine (pattern), come tutto ciò che fa è cercare la riga corrente per il modello fornito.
Forse qualcosa di simile (non ho ancora testato questo):
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();
}
mi sento di raccomandare si dimentica di usare scanner e basta usare un BufferedReader e un paio di modello di oggetti come che il metodo più flessibile per quello che si vuole fare.
Altri suggerimenti
Ecco un esempio utilizzando 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
pronto per essere eseguito:
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");
}
}
La prima linea è problematico.
- Hai bisogno di fuggire back-slash all'interno di stringhe letterali (
"i:\\1.txt"
non"i:\1.txt"
) - Il costruttore
Scanner
per la lettura da un file prende un argomentoFile
(o un argomentoInputStream
). Il costruttore che accetta un argomentoString
sta leggendo da tale stringa effettiva. Vedi le href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html" javadoc .
Prova
Scanner scanner = new Scanner(new File("i:\\1.txt"));
Alcuni codice di partenza:
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){}