2011-04-08 9 views
12

Así que esto es lo que tengo hasta ahora:Método para buscar cadena dentro del archivo de texto. A continuación, obtener las siguientes líneas hasta un cierto límite

public String[] findStudentInfo(String studentNumber) { 
       Student student = new Student(); 
       Scanner scanner = new Scanner("Student.txt"); 
       // Find the line that contains student Id 
       // If not found keep on going through the file 
       // If it finds it stop 
       // Call parseStudentInfoFromLine get the number of courses 
       // Create an array (lines) of size of the number of courses plus one 
       // assign the line that the student Id was found to the first index value of the array 
       //assign each next line to the following index of the array up to the amount of classes - 1 
       // return string array 
} 

sé cómo encontrar si un archivo contiene la cadena que estoy tratando de encontrar, pero no sé cómo recuperar toda la línea que está en.

Esta es la primera vez que publico, así que si he hecho algo mal por favor avíseme.

+1

Si esta es la tarea, debe ser etiquetado como tal. –

+0

¿Se puede agregar una muestra del archivo de entrada? – RonK

Respuesta

31

se puede hacer algo como esto:

File file = new File("Student.txt"); 

try { 
    Scanner scanner = new Scanner(file); 

    //now read the file line by line... 
    int lineNum = 0; 
    while (scanner.hasNextLine()) { 
     String line = scanner.nextLine(); 
     lineNum++; 
     if(<some condition is met for the line>) { 
      System.out.println("ho hum, i found it on line " +lineNum); 
     } 
    } 
} catch(FileNotFoundException e) { 
    //handle this 
} 
+0

Esto no me dará la línea que contiene la cadena studentNumber. –

+0

OK, mira otra vez ... –

+0

Oh ok, ya veo. ¡Gracias! –

2

Mientras lee el archivo, ¿ha considerado la lectura línea por línea? Esto le permitiría verificar si su línea contiene el archivo mientras está leyendo, y entonces podría realizar la lógica que necesitara basándose en eso.

Scanner scanner = new Scanner("Student.txt"); 
String currentLine; 

while((currentLine = scanner.readLine()) != null) 
{ 
    if(currentLine.indexOf("Your String")) 
    { 
     //Perform logic 
    } 
} 

Se puede usar una variable para contener el número de línea, o también podría tener un valor booleano que indica si ha pasado la línea que contiene la cadena:

Scanner scanner = new Scanner("Student.txt"); 
String currentLine; 
int lineNumber = 0; 
Boolean passedLine = false; 
while((currentLine = scanner.readLine()) != null) 
{ 
    if(currentLine.indexOf("Your String")) 
    { 
     //Do task 
     passedLine = true; 
    } 
    if(passedLine) 
    { 
     //Do other task after passing the line. 
    } 
    lineNumber++; 
} 
+0

Déjame intentar eso. Volvere a ti. –

+0

Solo un ejemplo, pero algo así debería funcionar. –

+0

¡Gracias! Me registraré para conseguirles algunos puntos –

0

estoy haciendo algo similar, pero en C++. Lo que debe hacer es leer las líneas en una a la vez y analizarlas (repase las palabras una a una). Tengo un bucle outter que recorre todas las líneas y dentro hay otro bucle que recorre todas las palabras. Una vez que encuentre la palabra que necesita, simplemente salga del ciclo y devuelva un contador o lo que quiera.

Este es mi código. Básicamente analiza todas las palabras y las agrega al "índice". La línea en la que estaba la palabra se agrega luego a un vector y se usa para hacer referencia a la línea (contiene el nombre del archivo, la línea completa y el número de línea) de las palabras indexadas.

ifstream txtFile; 
txtFile.open(path, ifstream::in); 
char line[200]; 
//if path is valid AND is not already in the list then add it 
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid 
{ 
    //Add the path to the list of file paths 
    textFilePaths.push_back(path); 
    int lineNumber = 1; 
    while(!txtFile.eof()) 
    { 
     txtFile.getline(line, 200); 
     Line * ln = new Line(line, path, lineNumber); 
     lineNumber++; 
     myList.push_back(ln); 
     vector<string> words = lineParser(ln); 
     for(unsigned int i = 0; i < words.size(); i++) 
     { 
      index->addWord(words[i], ln); 
     } 
    } 
    result = true; 
} 
+0

Aunque fue útil, el OP estaba pidiendo una solución basada en Java. Las operaciones de archivos C++ son considerablemente diferentes a las operaciones de archivos en Java, por lo que su respuesta no es del todo útil en este contexto. –

-1

Aquí está el código de TextScanner

public class TextScanner { 

     private static void readFile(String fileName) { 
      try { 
       File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds"); 
       Scanner scanner = new Scanner(file); 
       while (scanner.hasNext()) { 
       System.out.println(scanner.next()); 
       } 
       scanner.close(); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 
      } 

      public static void main(String[] args) { 
      if (args.length != 1) { 
       System.err.println("usage: java TextScanner1" 
       + "file location"); 
       System.exit(0); 
      } 
      readFile(args[0]); 
     } 
} 

Imprimirá texto con delimeters

1

Aquí es un método Java 8 para encontrar una cadena en un archivo de texto:

for (String toFindUrl : urlsToTest) { 
     streamService(toFindUrl); 
    } 

private void streamService(String item) { 
     String tmp; 
     try (Stream<String> stream = Files.lines(Paths.get(fileName))) { 
      tmp = stream.filter(lines -> lines.contains(item)) 
         .foreach(System.out::println); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
Cuestiones relacionadas