Java read and write file

0

Good companions. I have some problems with a program that I want to do in java, from a file doc.txt created previously, ask the user a word to search the contents of the file and generate a new result.txt that has the text of the file doc.txt but with the word searched in capital letters, the number of words in each file line and the total number of words. I attach the code.

import java.io.File;
import java.io.PrintStream;
import java.util.Scanner;

public class LecturaFitxer {

    public static void main(String[] args) {

        // Fichero que queremos leer
        File f = new File("C:\prueba\Documento.txt");
        Scanner lector = null;
        File k = new File("C:\prueba\Resultado.txt");
        Scanner r = new Scanner(System.in);

        try {
            System.out.print("Escribe la palabra que quieres buscar?");
            String palabra=r.next();
            // Leemos el contenido del fichero
            System.out.println("Leyendo el contenido fichero...");
            lector = new Scanner(f);
            //escribimos datos con esto
            PrintStream escriptor = new PrintStream(k);

            // Leemos la linia de cada fichero
            while (lector.hasNextLine()) {



         String linia = lector.nextLine();     // Guardamos la linia en string
                System.out.println(linia);          // Imprimimos la linia en string
            }
            lector.close();

        } catch (Exception ex) {
            System.out.println("Mensaje error: " + ex);
        }
    }
}
    
asked by gusanito12 08.05.2017 в 11:25
source

2 answers

1

use the toUpperCase method of the String class:

example:

String Str = new String("abc");
System.out.println(Str.toUpperCase());

returns:     ABC

link of the api:     link

    
answered by 08.05.2017 в 12:20
1

to get the specific word you could do an indexOf of the string:

int index = linia.indexOf(palabra); 

But you will not even need to find the position for your problem since you have the word to substitute. For that, java offers you the replace method:

public String replace(CharSequence target, CharSequence replacement)

that you would implement as:

String toUpper = palabra.toUpperCase();
linia.replace(palabra,toUpper);
    
answered by 08.05.2017 в 12:19