Pregunta

Tengo una pregunta acerca de escáner por favor, yo trabajo en una empresa pequeña; tenemos un software; se genera un archivo de texto grande; y debemos obtener alguna información útil a partir de ella; quiero escribir una sencilla aplicación con Java para ahorrar tiempo; ¿podría por favor me guía?

por ejemplo i quieren esta salida;

salida


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

Conde RFID: 2

y, por ejemplo, esto es mi archivo de texto, ya que cada archivo generado con nuestro software dispone de 14000 líneas:)

--------------------------
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;

lo prueba con este código fuente, pero no puedo manejarlo;

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

scanner.findInLine("RFID=");

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

Por favor, ayúdame;

Muchas gracias ...

¿Fue útil?

Solución

Bien su fuente sugiere no haría lo que quiere. Escáner rompe de entrada utilizando un delimitador. El delimitador predeterminado es de espacio en blanco (espacios, tabulaciones o saltos de línea). Scanner.hasNext () simplemente te dice si hay un nuevo espacio en blanco delimted token. Scanner.next () simplemente devuelve esa señal. Tenga en cuenta que ninguno de ellos se efectúan por Scanner.findInLine (patrón) que lo único que hace es buscar la línea actual para el patrón proporcionado.

Tal vez algo como esto (no he probado esto):

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();
}

Yo recomendaría que se olvide de usar escáner y sólo tiene que utilizar un BufferedReader y un par de patrón de objetos como ese método es más flexible de lo que quiere hacer.

Otros consejos

Este es un ejemplo usando 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

listo para correr:

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");
    }
}

Su primera línea es problemática.

  1. Es necesario para escapar de las copias de las barras dentro de los literales de cadena ("i:\\1.txt" no "i:\1.txt")
  2. El constructor Scanner para la lectura de un archivo toma un argumento File (o un argumento InputStream). El constructor que toma un argumento String es la lectura de esa cadena real. Ver las href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html" javadoc .

Trate

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

Parte del código de partida:

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){}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top