I am trying to read a text file and search for a word within it. The code is the following:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* El fichero se presupone que está en el directorio de trabajo y se llama Pruebas.txt
*/
public class Filtra {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in); //Creamos el Scanner que lee el teclado
System.out.println("Fichero de texto: "); //Introduccion del nombre del fichero
String filePath = teclado.next();
System.out.println("Palabra a buscar: "); //Introduccion de la palabra a buscar
String word = teclado.next();
System.out.println("Buscando las apariciones de la palabra"
+ " en el fichero: " + filePath);
try {
Scanner s = new Scanner(new File(filePath)); //Creamos el Scanner a partir del File. En este momento se comprueba que existe el mismo
int numLine = 0;
while (s.hasNextLine()) { //Mientras haya tokens en el archivo
String line = s.nextLine();
numLine++;
if (line.contains(word)) {
System.out.println(numLine + ": " + line);
}
}
s.close();
System.out.println("Fin del proceso.");
} catch (FileNotFoundException e) {
System.out.println("El fichero " + filePath + " no existe.");
}
teclado.close();
}
} // de main
The objective is that one enters by keyboard the name of a file (filePath) and a word to search for (word), then through the while the whole file is read. If the file is not found, the FileNotFoundException exception is thrown and the program ends. Well, when I enter the name of the file (Tests.txt) and search for a word, I get the message "The file Tests.txt does not exist." The content of the file is the following:
Scanner use.
Use of PrintWriter.Example of a file
with 10 lines and
16 words.
Pd: the file is in the same directory as the project.
You get the message "The file Tests.txt does not exist." because what it is really asking you for is the address of the file. Get the path from file properties
To read a file you need to use the filereader and bufferedreader object, I leave you an example below:
I hope I've helped.
If you pass only the name of the Java file, it looks in the directory where the project is located, not in its packages. Since my file was in a package, the exception was thrown
NotFileFound
.